Write JSON data to a file in Python
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.
|
1 2 3 4 5 6 7 8 9 |
import json import pprint with open('data.json', 'r') as f: data = f.read() json_data = json.loads(data) print(json_data) |
To write JSON to a file, call the json.dumps() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import json json_obj = json.loads('{"one": 1, "two": 2, "three": 3}') with open('data.json', 'w') as f: json.dump(json_obj, f) ''' data.json: {"one": 1, "two": 2, "three": 3} ''' |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import json json_str = '{"one": 1, "two": 2, "three": 3}' json_obj = json.loads(json_str) with open('data.json', 'w') as f: json.dump(json_obj, f, indent=2) ''' data.json: { "one": 1, "two": 2, "three": 3 } ''' |
2. If the indent is a string (such as '\t'), that string will indent each level.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import json json_str = '{"one": 1, "two": 2, "three": 3}' json_obj = json.loads(json_str) with open('data.json', 'w') as f: json.dump(json_obj, f, indent='\t') ''' data.json: { "one": 1, "two": 2, "three": 3 } ''' |
3. A zero or negative indent level or an empty string will only insert newlines.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import json json_str = '{"one": 1, "two": 2, "three": 3}' json_obj = json.loads(json_str) with open('data.json', 'w') as f: json.dump(json_obj, f, indent=0) ''' data.json: { "one": 1, "two": 2, "three": 3 } ''' |
That’s all about writing JSON data to a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)