以字符串形式加载具有特殊值的JSON对象

Loading JSON object with special values as a string

本文关键字:JSON 对象 字符串 加载      更新时间:2023-09-26

我正在尝试创建一个字符串JSON对象,以便使用json模块加载;但是,我遇到了一些问题,因为我的一些值是python TrueFalse,而不是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)

当然,如果我将TrueFalse更改为"True""False",我的条件也不满足,因为它们现在是字符串,并且将返回False

是否可以使用小写truefalse

>>> import json
>>> d = {'firstKey': True, 'secondKey': False}
>>> json.dumps(d)
'{"secondKey": false, "firstKey": true}'
>>> s = json.dumps(d)
>>> json.loads(s) == d
True