Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}')
like image 480
pokstad Avatar asked Jul 08 '11 16:07

pokstad


2 Answers

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
like image 103
Ignacio Vazquez-Abrams Avatar answered Nov 04 '22 09:11

Ignacio Vazquez-Abrams


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.

like image 40
Jasmijn Avatar answered Nov 04 '22 08:11

Jasmijn