pokstad
pokstad

Reputation: 3461

Is JSON syntax a strict subset of Python syntax?

JSON is very similar to Python syntax. Can all JSON objects directly convert to Python without error?

Example

The following is a valid JSON object:

// Valid JSON
{"foo":"bar"}

This object will directly translate to a Python dictionary with key "foo" and value "bar":

# Python
json_dict = eval('{"foo":"bar"}')

Upvotes: 19

Views: 1702

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798516

No. In particular, true, false, and null are not Python, although they do have direct equivalents in Python (True, False, and None respectively).

// Valid JSON
{"sky_is_blue":true}

But when used in Python...

# Python
>>> json_dict = eval('{"sky_is_blue":true}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'true' is not defined

Upvotes: 21

Jasmijn
Jasmijn

Reputation: 10452

This question has been answered (and the answer accepted) already, but I'd like to point out that the problem of true, false and null not being Python can be overcome by using the following code before evaluating JSON:

true = True
false = False
null = None

Of course, a JSON-parser is still better.

Upvotes: 6

Related Questions