13

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}]
ballade4op52
  • 2,142
  • 5
  • 27
  • 42
srs
  • 516
  • 1
  • 4
  • 20
  • 1
    Please add your code, demonstrating how it "yields entire json as one single item" – shx2 Nov 15 '13 at 08:20

1 Answers1

32

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
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • This just spits out the following error: ```TypeError: can't concat bytes to str``` – Jeremy Feb 06 '15 at 05:20
  • 1
    @JeremyCraigMartinez: There's no way I can guess where that exception is coming from with just the exception text. I suggest asking a question of your own, and including your code and a full traceback. – Blckknght Feb 06 '15 at 10:49
  • Sorry, just disregard that comment. I started just googling that along with ijson and found what I was looking for pretty quickly – Jeremy Feb 06 '15 at 20:22
  • 1
    This about drove me crazy, this answers "how to iterate over a JSON array in ijson" - which isn't exactly straightforward at a glance haha (vs. getting one big list item yielded) – Josh Jul 22 '15 at 22:01