21. Python JSON
Python JSON
JSON (JavaScript Object Notation) is a syntax for storing and exchanging data. It is text-based, lightweight, and language-independent, making it the universal standard for data exchange on the web (APIs). If your Python script talks to a server, it will almost certainly be using JSON.
Python has a built-in package called json, which allows you to seamlessly convert JSON strings into Python dictionaries, and vice-versa.
Importing the json Module
Since JSON support is built directly into Python's standard library, you do not need to install anything. Just import the module.
Parse JSON (JSON to Python)
If you receive a JSON string (for example, from a web API request), you can parse it by using the json.loads() method (loads stands for "load string"). The result will be a native Python dictionary.
Convert Python to JSON
If you have a Python object (a dictionary, list, etc.), you can convert it into a JSON string by using the json.dumps() method (dumps stands for "dump string"). This is necessary before sending data over a network.
What Types Can Be Converted?
You can convert Python objects of the following types, into JSON strings:
- dict (converts to JSON Object)
- list, tuple (converts to JSON Array)
- str (converts to JSON String)
- int, float (converts to JSON Number)
- True, False (converts to JSON true, false)
- None (converts to JSON null)
Formatting JSON (indent)
By default, json.dumps() outputs a dense string with no spaces, which is hard to read. Use the indent parameter to define the number of indents, creating beautifully formatted, human-readable JSON.
Sorting the Results
When you have a massive dictionary, finding specific keys can be tough. You can tell json.dumps() to sort the keys alphabetically using the sort_keys parameter.
Knowledge Check
Ready to test your understanding of 21. Python JSON?