以字符串形式加载包含特殊值的JSON对象

2 投票
1 回答
615 浏览
提问于 2025-04-17 15:27

我正在尝试创建一个字符串格式的 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 就会被返回。

1 个回答

4

你可以使用小写的 truefalse 吗?

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

撰写回答