简体   繁体   中英

Can valid JSON be invalid Python?

This is a simple questions that is really only a footnote in something I am writing:

Is any valid JSON not also valid Python?

I know the converse is true, ie Python data structures and scalars allow a variety of constructs that are not JSON. But for the most part, JSON seems to be a subset of Python syntax for defining (some) data structures.

The obvious stuff is covered. Strings are strings. Ints are ints. JSON "numbers" are read as Python floats (although RFC 8259 does not mandate that interpretation vs. fixed point, for example). Dicts are dicts. Lists are lists.

But maybe something in some obscure corner violates the subset relationship. For example, is there anything in the encoding of Unicode outside the BMP that is directly incompatible? Or maybe within Unicode surrogate pairs?

Or maybe something with numbers where some large number of digits after the decimal would be technically valid JSON but not Python? (I don't think so, but just trying to think of scenarios).

The most obvious thing is that true , false and null don't exist in Python. They are called True , False and None .

In addition, \/ in strings is interpreted as / in json and as \/ in Python:

>>> a = '"\/"'
>>> print(a)
"\/"
>>> print(eval(a))
\/
>>> print(json.loads(a))
/

Yes, you are correct, every valid JSON can be handled in Python. Python is a complete language, and JSON is a way of storing data (serialisation maybe?). Generally a language will support everything a JSON object can represent.

There would be different representation for sure like true in JSON is True in Python.

Since, JSON is way of storing data, and we can also pass it around HTTP requests, which are always processed by some server side language, which is expected to handle the JSON object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM