我正在处理一个python CGI脚本,它将接受一个JSON字符串作为输入然后处理它。在测试它时,我一直在抛出ValueErrors,我不知道为什么。
这是一个说明问题的摘录:
import json, pprint
a = """[{u'airline': u'JYX',
u'arrivaltime': u'2018-02-23 12:33:00.0',
u'departuretime': u'2018-02-23 09:21:00.0',
u'flightno': u'XX1021',
u'fltdate': u'2018-02-23',
u'fltdest': u'ZYHB',
u'fltdest_iata': None,
u'fltid': u'1035783',
u'fltori': u'ZSWZ',
u'fltori_iata': None,
u'in_timestamp': u'2018-02-23 12:40:00.0',
u'msid': u'INRP',
u'out_timestamp': u'2018-02-23 09:09:00.0',
u'tail': u'B-XXXX'},
{u'airline': u'JYX',
u'arrivaltime': u'2018-02-23 23:57:00.0',
u'departuretime': u'2018-02-23 20:42:00.0',
u'flightno': u'XX1022',
u'fltdate': u'2018-02-23',
u'fltdest': u'ZSWZ',
u'fltdest_iata': None,
u'fltid': u'1036068',
u'fltori': u'ZYHB',
u'fltori_iata': None,
u'in_timestamp': None,
u'msid': u'ONRP',
u'out_timestamp': u'2018-02-23 20:37:00.0',
u'tail': u'B-YYYY'}]"""
b = json.loads(a)
print "A:"
pprint.pprint(a)
print "B:"
pprint.pprint(b)
当我运行它时,我得到ValueError:期望属性名称:第1行第3列(char 2)
追溯:
Traceback (most recent call last):
File "dummy.py", line 31, in <module>
b = json.loads(a)
File "/Users/danmahoney/anaconda/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/Users/danmahoney/anaconda/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/danmahoney/anaconda/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 3 (char 2)
我已经通过在线验证器传递了JSON,所以我有点不知道是什么导致JSON对这些数据嗤之以鼻。任何指针都会受到赞赏。
答案 0 :(得分:0)
单引号在JSON中无效。您需要对字符串和键使用双引号。
答案 1 :(得分:0)
这不是有效的JSON。
u'string'
和None
是python字符串表示而不是JSON表示。
试试这个尺寸:
import json, pprint
a = """
[
{"airline": "JYX",
"arrivaltime": "2018-02-23 12:33:00.0",
"departuretime": "2018-02-23 09:21:00.0",
"flightno": "XX1021",
"fltdate": "2018-02-23",
"fltdest": "ZYHB",
"fltdest_iata": "",
"fltid": "1035783",
"fltori": "ZSWZ",
"fltori_iata": "",
"in_timestamp": "2018-02-23 12:40:00.0",
"msid": "INRP",
"out_timestamp": "2018-02-23 09:09:00.0",
"tail": "B-XXXX"},
{"airline": "JYX",
"arrivaltime": "2018-02-23 23:57:00.0",
"departuretime": "2018-02-23 20:42:00.0",
"flightno": "XX1022",
"fltdate": "2018-02-23",
"fltdest": "ZSWZ",
"fltdest_iata": "",
"fltid": "1036068",
"fltori": "ZYHB",
"fltori_iata": "",
"in_timestamp": "",
"msid": "ONRP",
"out_timestamp": "2018-02-23 20:37:00.0",
"tail": "B-YYYY"}]
"""
b = json.loads(a)
print "A:"
pprint.pprint(a)
print "B:"
pprint.pprint(b)
这就是JSON模块存在的原因。
如果您的数据确实是这样构建的,请尝试使用literal_eval
模块中的ast
。它将以安全(ish)方式将python代码评估为数据。