0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, I am getting the following error now "TypeError: string indices must be integers, not str" any advice?
just used json.loads(buf.getvalue()) before to decode the json data, and it worked! It's my second time ever using python. Trying to convert from PHP to Python. Thank you very much for your help, it is much appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.