如何在python中分离json的一部分?

2024-05-09 22:43:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以下格式的json,我只想保存其中的两部分。但我把它当作单独的角色。你能帮帮我吗

for data in results['results']:
   dictionary = dict(zip("title:", data['title']))
   dictionary = dict(zip("uuid:", data['uuid'])) 

Json

        results": [
            {
              "title": "subject1",
              "ja_pub_yyyy": 1395,
              "uuid": "86ae6",
              "external_link": null,
              "fulltext_status": 1,
},
  {
              "title": "subject2",
              "ja_pub_yyyy": 1395,
              "uuid": "86ae6",
              "external_link": null,
              "fulltext_status": 1,
}
]
    

新结果

    results": [
        {
          "title": "subject1",
          "id": "86ae6",
 },
        {
          "title": "subject2",
          "id": "86ae6",
 }]

Tags: datadictionaryuuidtitlelinkzipnullresults
3条回答

你也可以这样做

result = [{'title':r['title'],'uuid':r['uuid']} for r in results]

您没有正确地创建每个dict。更简单的是:

new_result = []
for data in results['results']:
    l = ((k,data[k]) for k in ("title","uuid"))
    dictionary = dict(l)
    new_result.append(dictionary)

我已经演示了如何收集每个dictionary

尝试循环json并将对象属性提取到新数组中。 例如:

results= [
            {
              "title": "subject1",
              "ja_pub_yyyy": 1395,
              "uuid": "86ae6",
              "external_link": None,
              "fulltext_status": 1,
},
  {
              "title": "subject1",
              "ja_pub_yyyy": 1395,
              "uuid": "86ae6",
              "external_link": None,
              "fulltext_status": 1,
}
]
res = []
for data in results:
    res.append({'name': data['title'], 'id': data['uuid']})
print(res)

相关问题 更多 >