DEV Community

Anže Pečar
Anže Pečar

Posted on

JSON in Python

The JavaScript Object Notation (JSON) is a lightweight data-interchange format that just so happens to be remarkably similar to Python's dict notation.

The two are so similar that you can copy JSON and paste it in the middle of your Python program and it will usually work:

>>> {
...     "my_object": {
...         "my_list": [1, "2", 3.0, 4.0e10]
...     },
...     "my_string": {
...         "escaping": "\"\" 🤔"
...     }
... }
{'my_object': {'my_list': [1, '2', 3.0, 40000000000.0]}, 'my_string': {'escaping': '"" 🤔'}}
Enter fullscreen mode Exit fullscreen mode

Unfortunately, this breaks down whenever you have those pesky booleans or nulls in your JSON:

>>> {
...     "my_null": null,
...     "my_bool": true,
...     "my_second_bool": false
... }
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'null' is not defined
Enter fullscreen mode Exit fullscreen mode

At this point, you might be tempted to do a search and replace that turns null, true & false into Python's None, True & False, but that's tedious and gets really annoying if you want to copy paste back and forth.

You could even be reasonable and use json.loads but then your JSON would be a string and your editor would no longer color highlight it correctly:

>>> import json
>>> json.loads("""
... {
...     "my_null": null,
...     "my_bool": true,
...     "my_second_bool": false
... }
... """)
{'my_null': None, 'my_bool': True, 'my_second_bool': False}
Enter fullscreen mode Exit fullscreen mode

Because colors are the most important thing in programming, there has to be a better way! And there is. Python allows us to use null, true and false as regular variable names. This means that we can do something like this:

>>> null=None; true=True; false=False
>>> {
...     "my_null": null,
...     "my_bool": true,
...     "my_second_bool": false
... }
{'my_null': None, 'my_bool': True, 'my_second_bool': False}
Enter fullscreen mode Exit fullscreen mode

Marvelous, isn't it? You can even put null=None; true=True; false=False in a separate python file (let's call PJ.py as a shorthand for PythonJson). Now you can do:

>>> from PJ import *
Enter fullscreen mode Exit fullscreen mode

And your python file will be ready to accept JSON!

Do make sure you wear a PJ like the one below when doing this, otherwise, people might think you are being serious 😅

#ViernesDePijamas"#ViernesDePijamas" by mrl.itesm2 is licensed under CC BY-NC-SA 2.0

Top comments (0)