-1

I collected this Json data from a script and am wondering how to parse the data to get the id attribute. Not even sure what to look up.

{
    "status": "success",
    "data": [
        {
            "notes": [],
            "handles": {
                "twitter": [
                    {
                        "networkinstance": "twitter",
                        "Uid": "fefewf32ff32f232f3f",
                        "id": "243425324242",
                        "@class": "Provider"
                    }
                ]
            },
            "id": "g43g5434g43f2f3",
            "tags": []
        }
    ]
}

1 Answers1

4

After decoding with the json module, this is just a dictionary containing lists and strings and other dictionaries:

import json

json_result = json.loads(json_string)
id = json_result['data'][0]['id']

Demo:

>>> import json
>>> sample = '''\
... {
...     "status": "success",
...     "data": [
...         {
...             "notes": [],
...             "handles": {
...                 "twitter": [
...                     {
...                         "networkinstance": "twitter",
...                         "Uid": "fefewf32ff32f232f3f",
...                         "id": "243425324242",
...                         "@class": "Provider"
...                     }
...                 ]
...             },
...             "id": "g43g5434g43f2f3",
...             "tags": []
...         }
...     ]
... }
... '''
>>> json_result = json.loads(sample)
>>> json_result['data'][0]['id']
u'g43g5434g43f2f3'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @Andrey: most JSON questions under the Python tag are really about how to index a nested structure. – Martijn Pieters Nov 24 '14 at 17:32
  • When running my shell script, I get a string indices must be integers error – techieIntern Nov 24 '14 at 21:45
  • @techieIntern did you try to index the undecoded JSON string perhaps? – Martijn Pieters Nov 24 '14 at 22:14
  • Sorry I didn't realize my data was changing constantly, hence why yours didn't work for me but your way is definitely the correct way to the question so thank you! Quick side note: the data I will need will be under the twitter part (is that called an attribute?) but it could also say Facebook. Could you point to where I need to look to find out how I could parse out the data without knowing the attribute name? – techieIntern Nov 25 '14 at 18:03
  • @techieIntern: you can loop over the dictionary to get keys, or use `.values()` to loop over the values ignoring the keys altogether, or use `.items()` to get key-value pairs. – Martijn Pieters Nov 25 '14 at 18:21