views:

254

answers:

1

I have the following case where I get the result of UTF-8 encoded HTTP response. I want to load the response content(JSON). However I don't know why I have to do 2 json.loads so that I get the final list:

result = urllib2.urlopen(req).read()
print result, type(result)
#=> "[{\"pk\": 66, \"model\": \"core.job\", \"fields\": {\"customer\": 1, \"created_ts\": \"2010-03-06 06:33:36\", \"log\": 66, \"process\": 1, \"ended_ts\": null, \"state\": \"PENDING\", \"started_ts\": null}}]" <type 'str'>
ret = json.loads(result)
print ret , type(ret)
#=> [{"pk": 66, "model": "core.job", "fields": {"customer": 1, "created_ts": "2010-03-06 06:33:36", "log": 66, "process": 1, "ended_ts": null, "state": "PENDING", "started_ts": null}}] <type 'unicode'>
ret = json.loads(ret)
print ret , type(ret)
#=>[{u'pk': 66, u'model': u'core.job', u'fields': {u'customer': 1, u'created_ts': u'2010-03-06 06:33:36', u'log': 66, u'process': 1, u'ended_ts': None, u'state': u'PENDING', u'started_ts': None}}] <type 'list'>

Any ideas?

+2  A: 

It looks like the repr() of the JSON string is what's being returned instead of the JSON string itself. So, something is broken on the server.

Ignacio Vazquez-Abrams
How can I get sure of your assumption?
khelll
If you examine the original string you'll notice that it has quotes at the beginning and end, and the internal quotes are escaped. This is not what a JSON string is supposed to look like. You can duplicate the effect by printing the result of `repr()` on a JSON string.
Ignacio Vazquez-Abrams