Saving a JSON File in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json
. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }
.
This module provides a method called dump()
which converts the Python objects into appropriate json objects.
import json # python object(dictionary) to be dumped dict1 = { "emp1" : { "name" : "Lisa" , "designation" : "programmer" , "age" : "34" , "salary" : "54000" }, "emp2" : { "name" : "Elis" , "designation" : "Trainee" , "age" : "24" , "salary" : "40000" }, } # the json file where the output must be stored out_file = open ( "myfile.json" , "w" ) json.dump(dict1, out_file, indent = 6 ) out_file.close() |
Output:
Note: For more information, refer to Working With JSON Data in Python.
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats.