简体   繁体   English

使用Python从JSON提取特定值

[英]Extract specific values from JSON using Python

I'm trying to figure out a way to display only the name and id from each object. 我正在尝试找出一种仅显示每个对象的名称和ID的方法。 I checked a lot of answers here already but I'm new to Python and I don't really know how to do this. 我已经在这里检查了很多答案,但是我是Python的新手,我真的不知道该怎么做。 This is my JSON file: 这是我的JSON文件:

{"tags": [
    {
      "tagGroup": "Named Tags",
      "lastConfig": null,
      "notes": null,
      "color": "#ffcc33ff",
      "name": "tag 3",
      "lastConfigTS": null,
      "fwVersion": null,
      "id": "a4da22e0296b"
    },
    {
      "tagGroup": "Named Tags",
      "lastConfig": null,
      "notes": null,
      "color": "#ff00ccdd",
      "name": "tag 4",
      "lastConfigTS": null,
      "fwVersion": null,
      "id": "a4da22e04235"
    },
    {
      "tagGroup": "Named Tags",
      "lastConfig": null,
      "notes": null,
      "color": "#ff00cccc",
      "name": "tag 5",
      "lastConfigTS": null,
      "fwVersion": null,
      "id": "a4da22e02225"
    }
  ]}

This is my current code: 这是我当前的代码:

import json
    from pprint import pprint

    with open('tags.json') as f:
        data = json.load(f)

    pprint(data["tags"][0]["id"])

I can get it to print only the first id, but I don't really know where to go from here. 我可以只打印第一个ID,但我真的不知道从这里去哪里。 Is there a way to print only all of name and id values? 有没有办法只打印所有名称和ID值?

Simply iterating through the list of dictionaries should do the trick for you. 简单地遍历字典列表应该可以解决问题。

import json
from pprint import pprint

with open('tags.json') as f:
    data = json.load(f)
for tag in data["tags"]:
    pprint(tag["id"])
    pprint(tag["name"])

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

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