简体   繁体   中英

Python json decode and search

I have a python script which gets a JSON file from a URL saves it to a variable called myjson . The next step I am looking to proceed through the data and select individual fields and output those fields to a file.

The following is an example of the json file i get

{
"data":
    {"111111111":
        {
        "date":"Wed Feb 12 17:36:01 UTC 2014",
        "left":null,
        "right":"test",
        "category":"test",
        "owner":"test",
        "name":"test",
        "id":123456789123,
        "status":"test",
        "severity":"test",
        "subject":"test",
        },
    "111111112":
        {
        "date":"Wed Feb 12 17:36:01 UTC 2014",
        "left":null,
        "right":"test",
        "category":"test",
        "owner":"test",
        "name":"test",
        "id":123456789123,
        "status":"test",
        "severity":"test",
        "subject":"test",
        }

}

Ideally I would like to create a file with the "111111111" field and the content of the "subject":"test" (only the test returned) for each entry in the json data structure

Decode the JSON with the json module , then just loop over the keys and values of the data dictionary; that's:

import json


json_data = json.loads(myjson)

for key, entry in json_data['data'].iteritems():
    print key, entry['subject']

If you are using Python 3, use myjson['data'].items(): instead.

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