Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse json with ijson and python

I have JSON data as an array of dictionaries which comes as the request payload.

[ 
    { "Field1": 1, "Feld2": "5" },
    { "Field1": 3, "Feld2": "6" }
]

I tried ijson.items(f, '') which yields the entire JSON object as one single item. Is there a way I can iterate the items inside the array one by one using ijson?

Here is the sample code I tried which is yielding the JSON as one single object.

f = open("metadatam1.json")
objs = ijson.items(f, '')
for o in objs:
     print str(o) + "\n"

[{'Feld2': u'5', 'Field1': 1}, {'Feld2': u'6', 'Field1': 3}]
like image 424
srs Avatar asked Nov 15 '13 08:11

srs


1 Answers

I'm not very familiar with ijson, but reading some of its code it looks like calling items with a prefix of "item" should work to get the items of the array, rather than the top-level object:

for item in ijson.items(f, "item"):
    # do stuff with the item dict
like image 192
Blckknght Avatar answered Sep 30 '22 04:09

Blckknght