简体   繁体   中英

Parsing a json (a response from freebase) in python

Parsing a json (a response from freebase) in python This question is regarding JSON parsing. I am querying freebase for some data and getting a JSON object. The response has a following structure

{
  "result": [
    {
      "attribute0": [
        "attrbVal0"
      ],
      "attribute1": [],
      "attribute2": "attrbVal1",
      "attribute3": [
        "val1",
        "val2"
      ],
      "creator": "abc",
      "key": [
        "val2",
        "val3"
      ]
    }
  ]
}

Please note that, the attributes can have zero values to any number of values. When there are no values it is represented as [] or null. The set of attributes is not known to me. It changes as the query changes,So I can't hard code the values like

result['attribute2'];

From the above JSON I want to get the attributes where the value is either [] or null . I have tried following things to get attributes and values,

print response.keys()

prints result

for r in response['result']: 
    print r

This prints everything inside result in one go. That is

print len(result) #prints 1

I have tried the following to get the list of attributes, but no luck.

result = response['result']
elem = json.loads(result);
keys = elem.keys()

So I am looking for the code to get all key value pairs from the above json and some explanation pointing out my mistake.

You can loop over the items of a dictionary, giving you both the keys and the values in pairs; this then lets you filter on the value:

for result in response['result']:
    for attrname, value in result.items():
        if not value:  # empty list or None
            print attrname

Note that response['result'] is a list, containing (presumably) one or more dictionary objects.

In Python both the empty list and None (the Python equivalent of the JSON null ) are considered false in a boolean context, so not value is True for those attributes whose values are either an empty list or null in the original JSON response.

Demo:

>>> response = {
...   "result": [
...     {
...       "attribute0": [
...         "attrbVal0"
...       ],
...       "attribute1": [],
...       "attribute2": "attrbVal1",
...       "attribute3": [
...         "val1",
...         "val2"
...       ],
...       "creator": "abc",
...       "key": [
...         "val2",
...         "val3"
...       ]
...     }
...   ]
... }
>>> for result in response['result']:
...     for attrname, value in result.items():
...         if not value:  # empty list or None
...             print attrname
... 
attribute1

So in your sample input, only attribute1 has an empty value.

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