【问题标题】:how to parse JSON to get specific value in Python如何解析 JSON 以在 Python 中获取特定值
【发布时间】:2018-01-06 17:42:01
【问题描述】:

请考虑以下数据:

    {
      "-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])

请帮我打印姓名和文字。 谢谢

【问题讨论】:

  • 哪个名字/文字?其中有四个。 “解析”是什么意思?
  • 有无数这样的对象,我想打印每个对象的名称和文本。

标签: python json object pprint


【解决方案1】:

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

[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...'}]

【讨论】:

  • 或者,list(d.values()) 返回完全相同的结果。
【解决方案2】:

也许你可以试试:

data={
      "-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?"
    }}

print(list(map(lambda x:(x['text'],x['name']),data.values())))

输出:

[('good to see you...', 'John'), ('hi', 'Joe'), ('hey', 'John'), ('how are you?', 'Joe')]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2021-12-14
    • 2020-03-26
    • 1970-01-01
    • 2018-09-15
    • 2013-04-10
    相关资源
    最近更新 更多