简体   繁体   中英

Parsing nested json with python

After submitting a request I have received the following json back:

{"type": [
{"ID": "all", "count": 1, "references": [
    { "id": "Boston,MA,02118", "text": "Boston,MA,02118", "val": "Boston,MA,02118", "type": 1 ,"zip": "02118","city": "Boston","state": "MA","lt": "42.3369","lg": "-71.0637","s": ""}
] }
] } 

I captured the response in variable j ,

>>> j
'{"type": [\r\n\t{"ID": "all", "count": 1, "references": [\r\n\t\t{ "id": "Boston,MA,02118", "text": "Boston,MA,02118", "val": "Boston,MA,02118", "type": 1 ,"zip": "02118","city": "Boston","state": "MA","lt": "42.3369","lng": "-71.0637","s": ""}\r\n\t] }\r\n] }'

and am trying to parse it:

>>> j['types']
TypeError: string indices must be integers, not str      

What am I doing wrong?

You've got a JSON string representation of a dictionary. But you're trying to use that string as a dictionary. That won't work; you need to parse it first, using the json module:

import json
obj = json.loads(j)
obj['types']

(There are libraries that can wrap up the whole "send a request, get a response, pull the body out of the response, make sure the content-type is right for JSON, parse it, raise an exception if anything goes wrong" for you. But if you're not using one, you can't skip any of the steps.)

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