简体   繁体   中英

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. I checked a lot of answers here already but I'm new to Python and I don't really know how to do this. This is my JSON file:

{"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. Is there a way to print only all of name and id values?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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