What is JSON?
How to work with JSON in Python?
Python has a built-in module called json (JSON Encoder and Decoder) for working with JSON. To work with JSON in Python, you need to import the json module first.
What is Python Object Serialization?
Serialization is the process of converting (encoding) Python objects into a stream of bytes (or string) to store the object in a database or file or transfer it over a network. The primary purpose of serialization is to preserve the state of an object so that it can be recreated in exactly the same state if needed. Serialization itself is insecure, and Python objects containing sensitive data must be additionally protected and transmitted only over secure network connections.
How does JSON Encoder convert Python object to JSON string?
How to serialize complex Python objects?
If the JSON Encoder encounters a non-base Python object, it will throw a TypeError exception when converting the Python object to a JSON string. The code below will raise a "TypeError: Object of type Point is not JSON serializable" exception because of the json.dumps() method does not know how to serialize a Point class object to a JSON string. We will show below how to fix this error and teach json.dumps() method to work with complex Python objects.
Serializing complex Python objects to JSON with the json.dumps() method
The json module provides an extensible API for encoding (or dumping) basic Python objects into JSON data strings and decoding (or parsing) JSON data strings into Python objects. The JSON dump method takes an optional cls parameter to pass your own JSON encoder implementation. The custom JSON encoder will be used for Python to JSON conversions instead of the base JSONEncoder class.
As you can now see, json.dumps() does not throw an exception and converts the non-basic object to a JSON string.
Python to JSON Dump Method Syntax
- skipkeys - when True, then do not throw a TypeError for non-basic types (skip these objects)
- ensure_ascii - when True, escape all non-ASCII characters
- indent - if specified then pretty-print JSON with that indent level
- separators - separators to use when generating JSON output. To get a compact JSON use (',', ':').
- sort_keys - if True, then dictionaries are sorted by key
How to dump a Python object to a JSON file?
To serialize a Python object to a JSON file, you can use the json.dump() method (without the "s") from the json module. The json.dump() method is similar to json.dumps(), but it takes an additional File Pointer (fp) object and outputs the generated JSON to that file. The fp.write() method must support str input as the json module creates strings (not bytes).
How to pretty print the JSON using json.dumps()?
You can pretty-print the JSON output by specifying the indent level to the json.dumps() method.
How to get compact JSON output using json.dumps()?
To get a compact JSON without spaces or line breaks, you can pass the separators==(',', ':') to the json.dumps() method and avoid using the indent.
How to sort data in JSON using json.dumps()?
To sort the data in the generated JSON string, pass the sort_keys=True parameter to the json.dumps() method.
How can I prevent json.dumps() from throwing exceptions?
If the Python dictionary contains a non-basic object, json.dumps() method will throw a TypeError exception by default. To prevent json.dumps() from throwing exceptions, pass the skipkeys=True parameter to the json.dumps() method. This will tell json.dumps() to ignore such keys.
How to handle non-ASCII characters when using json.dumps()?
By default, the json.dumps() method will escape all non-ASCII characters in the resulting JSON. To force the json.dumps() method to store non-ASCII characters in JSON, pass sure_ascii=False to the json.dumps() call. Note that this may break the JSON and prevent some clients from reading it.
What is the difference between json.dumps() and json.loads()?
The json.loads() method is the opposite of json.dumps(). It takes a JSON string and converts it to a Python object, while json.dumps() takes a Python object and converts it to a JSON string. Use the json.loads() method to parse JSON strings and files and convert them into Python objects.
The json.dumps() method allows you to dump Python objects to JSON strings in a simple and elegant way. The json.dumps() method is very flexible; you can pretty-print the generated JSON strings or create compact JSON files. The json.dumps() method has a rich set of options for handling non-ASCII characters, sorting JSON keys, and working with floating-point numbers, and can be easily extended with custom JSON encoders.