2

I've a JSON string like the one shown in json1. I'm trying to parse this as a JSON but it doesnt seem to work. What is going wrong?

import json

string1 = "[]"
list1 = "['hi','bye']"
json1 = "{'genre': ['Action', 'Comedy']}"

print json.loads(string1)
print json.loads(list1)
print json.loads("{'genre': ['Action', 'Comedy']}")

It gives me the error

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

2 Answers2

5

json expects double quoted strings, you have single-quoted strings. You can load your strings using ast.literal_eval:

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

result:

{'genre': ['Action', 'Comedy']}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
2

JSON (unlike JavaScript or 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

Because of this, and because Python tends to prefer single-quoted strings, the repr() of a Python object is almost always invalid JSON. You must use json.dumps() instead.

>>> v = ["hi", "bye"]
>>> repr(v)
"['hi', 'bye']"
>>> json.dumps(v)
'["hi", "bye"]'
zwol
  • 135,547
  • 38
  • 252
  • 361