Luca Luca - 9 months ago 41
JSON Question

json object returned by http response

I am using python and django to develop some REST APIs. I have a question about the JSON unicode string returned by the requests call. So, I am doing something like:

resp = requests.get(self.url)
if resp.status_code is status.HTTP_200_OK:
obj = json.loads(resp.json())

With this I can iterate over the entries as:

for o in obj:
print o

This prints something like:

{u'pk': 1, u'model': u'aslapp.imagetypemodel', u'fields': {u'type': u'PNG'}}
{u'pk': 2, u'model': u'aslapp.imagetypemodel', u'fields': {u'type': u'JPG'}}

However, I read that the
call should call this
method internally and will take care of the encoding stuff. However, just doing:

obj = resp.json()
for o in obj:
print o

Just iterates over each character in the unicode string. So am I supposed to run it through the
method again if I want to iterate through the JSON entries? What would be the correct way to iterate through all the JSON records returned returned by

Answer Source

You are correct, resp.json() does call json.loads() for you.

Therefore, if resp.json() returns a string, then that suggests that the API has json encoded the data twice. For example, it is returning "{\"pk\": 1}" instead of {"pk": 1}.

If you don't have any control over the API, then you'll have to decode it twice to get the Python object.