Philoktetes Philoktetes - 1 month ago 18
JSON Question

How do I remove an extra square bracket from JSON in Python?

I have JSON of the following form:

{"blah":
[
[
{"first":
{"something":"that","something":"else","another":"thing","key":"value"}...[etc.]
}
]
]
}


that I'm trying to parse in Python. I've imported json (or simplejson, depending on what version of Python you're using) and everything goes pretty well until I get to this block:

for result in page['blah']:
that = result['first']
a_list.append(that)


which throws the error "TypeError: list indices must be integers, not str".

I'm pretty sure this error is due to the extra pair of square-bracket that makes the JSON inside look like a list.

My question, assuming that's the case, is, How do I remove it and still have valid JSON to parse as dictionaries?

Other workarounds welcome. If I need to supply more info, let me know. Thanks!

(Added the missing curly bracket and changed a couple of confusing terms--I was trying to come up with generic terms on the fly, sorry for any confusion.)

Answer

If there's always exactly one "extra" set of array brackets:

for result in page['blah']:
    that = result[0]['this']
    list.append(that)