21
votes

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.

3
Thanks everyone for your help. I realized that I'm asking the wrong question, since I'm trying to debug an API sent to me that uses django-piston and I haven't used it before. My actual question is related to django-piston and why the Content-Type of my response was always being set to text-plain instead of application/json whenever the response is HTTP CREATED (201). I will ask this as a separate question, since the original question is irrelevant to the actual problem (though the answers about the behavior of JSON are interesting!). - Nick Ruiz

3 Answers

35
votes

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])
5
votes

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?

3
votes

i have use json on django , i use this :

import simplejson as json
#to encode
final= {'first':first_data,'second':second_data}
json.dumps(final)
#to decode this is the example from python's api 
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')