简体   繁体   English

Python - 如何使用 json.load 遍历 JSON 数据

[英]Python - how can I iterate through JSON data with json.load

I have the below JSON, which I parse with json.load()我有下面的 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"
    },

I tried to iterate through the messages to search for strings inside each value.我试图遍历消息以在每个值中搜索字符串。

import json 

data = json.load(f)
   
for msg in data['messages']:

    search = 'Jo'

    if search in str(msg['sender_name']) :
      print (msg['sender_name'])

This works and outputs a "Joe Bloggs" or "John Doe" string for every message object.这可以为每条消息 object 输出一个“Joe Bloggs”或“John Doe”字符串。

If I try and search for any other keys , timestamp, content, type, I get a KeyError, eg trying to search for all messages where they participants use the word "Hello".如果我尝试搜索任何其他键、时间戳、内容、类型,我会收到 KeyError,例如尝试搜索参与者使用单词“Hello”的所有消息。

if search in str(msg['content']) :
          print (msg['content'])

results in a key error:导致关键错误:

in <module>
    if search in str(msg['content']) :
KeyError: 'content'

I think I am not understanding something about json.load and Python dictionaries/lists.我想我不了解 json.load 和 Python 词典/列表。 Why is it that msg[sender_name] works but not msg[content]?为什么 msg[sender_name] 有效但 msg[content] 无效? Thanks谢谢

I just tried.get('content') and it worked...我刚刚尝试过.get('content') 并且它起作用了......

 search = 'Thing I am searching for'

    if search in str(msg.get('content')) :
        print (msg.get('content'))

If anyone could elaborate I would appreciate it.如果有人能详细说明,我将不胜感激。 I've found a solution, but I'd like to understand the 'why'.我找到了解决方案,但我想了解“为什么”。 Thanks谢谢

You can avoid KeyError with the.get() method on the dictionary您可以使用字典上的 .get() 方法避免 KeyError

if search in str(msg.get('content')):
    print(str(msg.get('sender_name')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM