11

私はPythonでJSONオブジェクトをロードする方法を理解しようとしてきました。

   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

どこが間違っているのですか?

エラーコード(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);

真のコード(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));

真のコード(Python):

   def do_POST(self):
    length = int(self.headers['Content-Length'])
    decData = self.rfile.read(length)
    postData = json.loads(decData)
    postData = json.loads(postData)
4

3 に答える 3

9

JSONデータは余分な引用符で囲まれてJSON文字列になり、その文字列に含まれるデータはJSONではありません

代わりに印刷repr(decData)すると、次のようになります。

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

そして、JSONライブラリはそれをリテラルの内容を持つ1つの文字列として正しく解釈しています{'name' : 'journal2'}。外側の引用符を削除した場合、JSON文字列は常に二重引用符で囲む必要があるため、含まれている文字は有効なJSONではありません。

関係するすべてのjsonモジュールについてdecData、同様に含まれている可能性が"This is not JSON"ありpostData、に設定されている可能性がありu'This is not JSON'ます。

>>> import json
>>> decData = '''"{'name' : 'journal2'}"'''
>>> json.loads(decData)
u"{'name' : 'journal2'}"
>>> json.loads(json.loads(decData))
Traceback (most recent 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
    return _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)

この文字列を生成しているものは何でも修正してください。ビューは問題ありません。壊れているのは入力です。

于 2013-02-08T11:31:09.860 に答える