【发布时间】:2020-12-15 16:19:17
【问题描述】:
我有下面的 JSON,我用 json.load() 解析它
{
"participants": [
{
"name": "Joseph Bloggs"
},
{
"name": "John Doe"
}
],
"messages": [
{
"sender_name": "Joseph Bloggs",
"timestamp_ms": 1606943360034,
"content": "Hello John",
"type": "Generic"
},
{
"sender_name": "John Doe",
"timestamp_ms": 1606943285176,
"content": "Hi Joe",
"type": "Generic"
},
我尝试遍历消息以在每个值中搜索字符串。
import json
data = json.load(f)
for msg in data['messages']:
search = 'Jo'
if search in str(msg['sender_name']) :
print (msg['sender_name'])
这工作并为每个消息对象输出一个“Joe Bloggs”或“John Doe”字符串。
如果我尝试搜索 任何其他键、时间戳、内容、类型,我会得到一个 KeyError,例如尝试搜索参与者使用“Hello”一词的所有消息。
if search in str(msg['content']) :
print (msg['content'])
导致关键错误:
in <module>
if search in str(msg['content']) :
KeyError: 'content'
我想我不了解 json.load 和 Python 字典/列表。为什么 msg[sender_name] 有效但 msg[content] 无效?谢谢
【问题讨论】:
-
所有邮件都有
content吗? -
请包含一个有效的 JSON 文件和产生您遇到的错误的可运行代码。很难按原样为您提供帮助,因为有很多事情可能会出错。
-
@DaniMesejo 不,不是所有的消息都有内容,现在我想想……