为什么json.loads()可以处理某些字符串?

时间:2016-12-25 18:36:57

标签: python json

我有一个像import json string1 = "[]" list1 = "['hi','bye']" json1 = "{'genre': ['Action', 'Comedy']}" print json.loads(string1) print json.loads(list1) print json.loads("{'genre': ['Action', 'Comedy']}") 中所示的JSON字符串。我试图将其解析为JSON但它似乎无法工作。出了什么问题?

Traceback (most recent call last):
  File "python", line 8, in <module>
ValueError: No JSON object could be decoded

它给了我错误

{{1}}

2 个答案:

答案 0 :(得分:6)

json期望双引号字符串,你有单引号字符串。您可以使用ast.literal_eval加载字符串:

import ast
print(ast.literal_eval("{'genre': ['Action', 'Comedy']}"))

结果:

{'genre': ['Action', 'Comedy']}

答案 1 :(得分:2)

JSON(与JavaScript或Python不同)only allows double-quoted strings

>>> print json.loads('["hi","bye"]')
[u'hi', u'bye']

>>> print json.loads("['hi','bye']")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

正因为如此,并且因为Python倾向于选择单个引用的字符串,所以Python对象的repr()几乎总是无效 JSON。您必须改为使用json.dumps()

>>> v = ["hi", "bye"]
>>> repr(v)
"['hi', 'bye']"
>>> json.dumps(v)
'["hi", "bye"]'