Ciaran
Ciaran

Reputation: 1149

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

Upvotes: 0

Views: 744

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121942

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.

Upvotes: 2

Related Questions