开发者

Is JSON syntax a strict subset of Python syntax?

JSON is very similar to Python syntax. Can all JSON objects directly convert to Python wit开发者_StackOverflow社区hout 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"}')


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜