Skip to main content
 首页 » 编程设计

python之如何解析 JSON 以在 Python 中获取特定值

2024年09月07日13cmt

请考虑以下数据:

    { 
      "-L0B6_KJJlhWIaV96b61" : { 
                     "name" : "John", 
                     "text" : "hey" 
    }, 
      "-L0B6cN4SV59tuNVWh_1" : { 
                     "name" : "Joe", 
                     "text" : "hi" 
    }, 
      "-L0B6epDdv1grl7t5kdM" : { 
                     "name" : "John", 
                     "text" : "good to see you..." 
    }, 
      "-L0B6fsyjAm4B_CWXKFs" : { 
                     "name" : "Joe", 
                     "text" : "how are you?" 
    } 

现在如何在 Python 中解析这个 JSON 文件的名称和文本? 我有一个像这样的大数据集。如您所见,在这种情况下对象是可变的,所以我不能简单地写:

         # To print the name 
         pprint(data[object_variable][0]) 

请帮我打印名称和文本。 谢谢

请您参考如下方法:

如果我理解正确,请使用列表理解(或生成器)来放置字典的值:

[v for _, v in data.items()] 

当然你可以直接打印或者操作,不需要中间列表。

所以:

In [10]: d 
Out[10]:  
{'-L0B6fsyjAm4B_CWXKFs': {'name': 'Joe', 'text': 'how are you?'}, 
 '-L0B6cN4SV59tuNVWh_1': {'name': 'Joe', 'text': 'hi'}, 
 '-L0B6_KJJlhWIaV96b61': {'name': 'John', 'text': 'hey'}, 
 '-L0B6epDdv1grl7t5kdM': {'name': 'John', 'text': 'good to see you...'}} 
 
In [11]: [v for _, v in d.items()] 
Out[11]:  
[{'name': 'Joe', 'text': 'how are you?'}, 
 {'name': 'Joe', 'text': 'hi'}, 
 {'name': 'John', 'text': 'hey'}, 
 {'name': 'John', 'text': 'good to see you...'}]