Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict to JSON via json.loads:

Tags:

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.

like image 242
Nick Ruiz Avatar asked Dec 31 '10 18:12

Nick Ruiz


People also ask

What is the difference between JSON load and JSON loads?

The json. load() is used to read the JSON document from file and The json. loads() is used to convert the JSON String document into the Python dictionary.

What does JSON loads do in Python?

loads() json. loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary.

What is JSON dumps and JSON loads?

json loads -> returns an object from a string representing a json object. json dumps -> returns a string representing a json object from an object.


1 Answers

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]) 
like image 127
Daniel Roseman Avatar answered Oct 14 '22 03:10

Daniel Roseman