JSON: Work with JSON - detailed Serialization

To work with JSON (string or file containing a JSON object), you can use Python's built-in json module. 

Copy
import json

Write JSON to a file

The process of encoding JSON is called serializationTo write JSON to a file in Python, we use the json.dump()method.

Copy

Example

import json

cake_dict = {"name": "Banana miracle",
"toppings": ["Chocolate", "Mint frosting"],
"Filling": True,
"price": 35
}

with open('cake.txt', 'w') as json_file:
  json.dump(cake_dict, json_file)

In this example, we have opened a file namedcake.txt in writing mode using'w'. This file will be automatically created in case it doesn't exist. Thenjson.dump() will save in the the cake.txt file the transformed cake_dict. It will be convertedto a JSON string which will look like that:

Copy
{"name": "Banana miracle", "toppings": ["Chocolate", "Mint frosting"], "Filling": true, "price": 35}
{"name": "Banana miracle", "toppings": ["Chocolate", "Mint frosting"], "Filling": true, "price": 35}

Python pretty print JSON

To analyze and debug JSON data, we may need to print it in a more human-readable format. This can be done by passing additional parameters indent an dsort_keys to json.dumps()method. Both of them are already implemented by the json module.

Copy

Example

import json

cake_string = '{"name": "Banana miracle", "Topping": "Chocolate", "portions": [1.5, 2, null]}'

# Getting dictionary
cake_dict = json.loads(cake_string)

# Pretty Printing JSON string back
# Use the sort_keys parameter to specify if the result should be sorted or not:
print(json.dumps(cake_dict, indent = 4, sort_keys=True))

You can also define the separators, which default value is (", ", ": ") - this means using a comma and a space to separate each object, and a colon and a space to separate keys from values:

Copy

Example

# Use the "separators" parameter to change the default separator:
json.dumps(cake_dict, indent=4, separators=(". "" = "))

When you run the program, the output will be:

Copy
{
    "name": "Banana miracle",
    "portions": [
        1.5,
        2,
        null
    ],
    "Topping": "Chocolate"}

In the above example, we have used 4 spaces for indentation. And, the keys are sorted in ascending order.

By the way, the default value of indentisNone. And, the default value of sort_keys is False.