This post will discuss how to read and write JSON data from a file in Python.

The standard way to read and write JSON data from a file is using the json module.

To read a JSON file, you can simply call the json.loads() function.

Download Code

 
To write JSON to a file, call the json.dumps() function.

Download Code

 
The json.dumps() function selects the most compact representation of json by default. For pretty-printing the json, you can specify the indent argument.

 
1. A positive indent level indents that many spaces per level, i.e., JSON will be pretty-printed with that indent level.

Download Code

 
2. If the indent is a string (such as '\t'), that string will indent each level.

Download Code

 
3. A zero or negative indent level or an empty string will only insert newlines.

Download Code

That’s all about writing JSON data to a file in Python.