Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can valid JSON be invalid Python?

Tags:

python

json

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, i.e. 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).

like image 638
David Mertz Avatar asked Jan 01 '23 01:01

David Mertz


1 Answers

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))
/
like image 176
wastl Avatar answered Jan 13 '23 02:01

wastl