How to Create JSON file in Python

Here’s a sample Python logic to create a JSON file. JSON’s purpose is to exchange data between applications.

How to create a JSON file

Here is the logic. In the data object, you can find the JSON information.

data = {
  'value1': 1,
 'value2': 2,
'a_dict_of_values' : {
'd1': 'hello',
'd2': 'world'
},
'value3': 1.234
}
with open('data.json', 'w', encoding='utf-8') as f:
  json.dump(data, f, ensure_ascii=False, indent=4)

JSON is a key/value structure similar to a Python dictionary. The With Open statement opens the file and assigns it to the object f. 

The output file is data.json, and the mode is W, which is write mode.┬áThe format encoding=’utf-8′ tells data how it writes to the output file.

The JSON.dump writes data to the output file. The four arguments are VIZ: data, f, ensure_ascii, and indent=4. The indent=4 writes data to output in a readable format. 

The ensure_ascii value according to python docs: If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.

Advertisements

Creating JSON file in Python IDLE

Do import JSON, which is the first step that pulls the JSON package into the program. So we can use all the available JSON methods.

Import json package
Python logic to create a JSON file

The result of the python script

After you run the script, an output file of data.json will create and it has all the formatted JSON data.

Python JSON file
Output from the python script

Reference books

Related posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.