I’ve been trying to figure out how to load JSON objects in Python.
def do_POST(self):
length = int(self.headers['Content-Length'])
decData = str(self.rfile.read(length))
print decData, type(decData)
"{'name' : 'journal2'}" <type 'str'>
postData = json.loads(decData)
print postData, type(postData)
#{'name' : 'journal2'} <type 'unicode'>
postData = json.loads(postData)
print postData, type(postData)
# Error: Expecting property name enclosed in double quotes
Where am I going wrong?
Error Code (JScript):
var data = "{'name':'journal2'}";
var http_request = new XMLHttpRequest();
http_request.open( "post", url, true );
http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(data);
True Code (JScript):
var data = '{"name":"journal2"}';
var http_request = new XMLHttpRequest();
http_request.open( "post", url, true );
http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(JSON.stringify(data));
True Code (Python):
def do_POST(self):
length = int(self.headers['Content-Length'])
decData = self.rfile.read(length)
postData = json.loads(decData)
postData = json.loads(postData)
Your JSON data is enclosed in extra quotes making it a JSON string, and the data contained within that string is not JSON.
Print
repr(decData)instead, you’ll get:and the JSON library is correctly interpreting that as one string with the literal contents
{'name' : 'journal2'}. If you stripped the outer quotes, the contained characters are not valid JSON, because JSON strings must always be enclosed in double quotes.For all the
jsonmodule is concerned,decDatacould just as well have contained"This is not JSON"andpostDatawould have been set tou'This is not JSON'.Fix whatever is producing this string, your view is fine, it’s the input that is broken.