0

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?

1 Answer 1

5

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.)

Sign up to request clarification or add additional context in comments.

3 Comments

I think he also misspell the key type
@FlilyHsuL Yeah, I think you're right. But at least he'll get a KeyError instead of a TypeError, and hopefully that'll be easier to understand. (Or, hopefully, he'll read your comment…)
Thank you, but that was just a typo - Bill

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.