如何从多个JSON对象python的特定键中解析值
Posted
技术标签:
【中文标题】如何从多个JSON对象python的特定键中解析值【英文标题】:How to parse values from a specific key of multiple JSON objects python 【发布时间】:2021-10-31 23:36:15 【问题描述】:我正在尝试从下面的 JSON 中解析关键的“标签”。
data = [
"12233":
"title": "The Title",
"id": "12233",
"tags": ["tag1", "tag2", "tag3"],
,
"122223":
"title": "The Title",
"id": "122223",
"tags": ["tag4", "tag5", "tag6"],
,
"122344":
"title": "The Title",
"id": "122344",
"tags": ["tag7", "tag8", "tag9"],
]
到目前为止我已经尝试过了,
data = data[0]
tags_list = []
for tags in data:
tags_list.append(tags["122344"])
print(tags_list)
但它只提取第一个对象,我希望结果是这样的,
tags_list = ["tag1", "tag2", "tag3", "tag4", "tag5", "tag6","tag7", "tag8", "tag9"]
【问题讨论】:
尝试使用列表压缩 【参考方案1】:这能解决你的问题吗?
tags_list = [item for k in data for t in k for item in k[t]['tags']]
【讨论】:
【参考方案2】:对字典 data[0] 的所有值使用 itemgetter 并将所有项目求和到空列表 []
from operator import itemgetter
data = [
"12233":
"title": "The Title",
"id": "12233",
"tags": ["tag1", "tag2", "tag3"],
,
"122223":
"title": "The Title",
"id": "122223",
"tags": ["tag4", "tag5", "tag6"],
,
"122344":
"title": "The Title",
"id": "122344",
"tags": ["tag7", "tag8", "tag9"],
]
tag_getter = itemgetter('tags')
# map to get list of all tags
# Adding all the list of tags to []
sum(map(tag_getter, data[0].values()), [])
['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6', 'tag7', 'tag8', 'tag9']
如果要合并列表中所有条目的所有标签,请使用
from operator import itemgetter
tag_getter = itemgetter('tags')
def all_tags(d):
return sum(map(tag_getter, d.values()), [])
sum(map(all_tags, data), [])
【讨论】:
Python 中的 Lambda 被设计为匿名函数。给变量赋值是没有意义的,使它成为一个命名函数。这被认为是不好的做法。如果需要,请改为定义一个函数。请参阅 (***.com/a/25010243/6789321) 和 (python.org/dev/peps/pep-0008/#programming-recommendations)。【参考方案3】:您需要两个循环来遍历内部字典,而不是单个循环。试试这个:
tags_list = []
for k in data:
for t in k:
tags_list.extend(k[t]['tags'])
输出tags_list
:
['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6', 'tag7', 'tag8', 'tag9']
【讨论】:
以上是关于如何从多个JSON对象python的特定键中解析值的主要内容,如果未能解决你的问题,请参考以下文章