Reputation: 36205
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?
Upvotes: 0
Views: 378
Reputation: 365597
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.)
Upvotes: 5