Wednesday, 15 August 2012

python json.loads don't work -



python json.loads don't work -

it's code. i've been tyring figure out how 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 going wrong?

error code jscript

var info = "{'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 info = '{"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)

i apologize english. all

your json info enclosed in quotes making json string, and info contained within string not json.

print repr(decdata) instead, you'll get:

'"{\'name\' : \'journal2\'}"'

and json library correctly interpreting 1 string literal contents {'name' : 'journal2'}. if stripped outer quotes, contained characters not valid json, because json strings must enclosed in double quotes.

for json module concerned, decdata have contained "this not json" , postdata have been set u'this not json'.

>>> import json >>> decdata = '''"{'name' : 'journal2'}"''' >>> json.loads(decdata) u"{'name' : 'journal2'}" >>> json.loads(json.loads(decdata)) traceback (most recent phone call last): file "<stdin>", line 1, in <module> file "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads homecoming _default_decoder.decode(s) file "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) file "/opt/local/library/frameworks/python.framework/versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) valueerror: expecting property name: line 1 column 1 (char 1)

fix whatever producing string, view fine, it's input broken.

python json

No comments:

Post a Comment