以字符串形式加载包含特殊值的JSON对象
我正在尝试创建一个字符串格式的 JSON 对象,以便使用 json
模块加载;不过我遇到了一些问题,因为我的一些值是 Python 的 True
和 False
,而不是 Unicode 字符串。例如,我想这样做:
>>> newDict = json.loads(u'{"firstKey": True, "secondKey": False}')
>>> newDict.get('firstKey') == True
True
但是我得到了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib64/python2.6/json/decoder.py", line 185, in JSONObject
raise ValueError(errmsg("Expecting object", s, end))
ValueError: Expecting object: line 1 column 13 (char 13)
当然,如果我把 True
和 False
改成 "True"
和 "False"
,那么我的条件也不成立了,因为它们现在变成了字符串,False
就会被返回。
1 个回答
4
你可以使用小写的 true
和 false
吗?
>>> import json
>>> d = {'firstKey': True, 'secondKey': False}
>>> json.dumps(d)
'{"secondKey": false, "firstKey": true}'
>>> s = json.dumps(d)
>>> json.loads(s) == d
True