2

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

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

4

1 回答 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
于 2013-02-11T01:12:58.090 回答