Python dict to JSON via json.loads:


I have troubleshooting some code that uses HTTP POST to send data and should return a JSON result whose contents are a dictionary. I am using an XML-RPC wrapper to expose this service. When the wrapper receives the dict information from the http response variable, the dict contents are in a string in this form:

{'created': datetime.datetime(2010, 12, 31, 19, 13, 8, 379909), 'worker': u'GoogleWorker', 'ready': False, 'request_id': '8f1381853a444a42a37ae5152a3af947', 'owner': u'admin', 'shortname': u'test19'}

I'm trying to convert the string below into a JSON result using the following statement:

result = json.loads(response[1])

However, when I try to use json.loads to convert the data to JSON, I get the following error: Fault: <Fault 1: "<type 'exceptions.ValueError'>:Expecting property name: line 1 column 1 (char 1)">

I manually tried to convert the above string to JSON, but I get the same error. Is the dict malformed in some way? Is it due to unicode? I also tried setting the locale to UTF-8, but that was unsuccessful.

Any help would be greatly appreciated.

12/31/2010 6:27:37 PM

Accepted Answer

You are trying to use the wrong method. json.loads is for loading JSON to Python. If you want to convert Python to JSON, you need json.dumps.

result = json.dumps(response[1])
12/31/2010 8:27:05 PM

That dict is in Python dict literal format, not JSON. You can do:

import ast
result = ast.literal_eval(response[1])

to read in the response in that format. Are you sure that Django hasn't already JSON-decoded the response?

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow