Python Write JSON to File

Python Write JSON to File

Python Write JSON to File

You can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively.

Following is a step by step process to write JSON to file.

  1. Prepare JSON string by converting a Python Object to JSON string using json.dumps() function.
  2. Create a JSON file using open(filename, ‘w’) function. We are opening file in write mode.
  3. Use file.write(text) to write JSON content prepared in step 1 to the file created in step 2.
  4. Close the JSON file.

Example 1: Write JSON (Object) to File

In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json.

Python Program

import json

aDict = {"a":54, "b":87}
jsonString = json.dumps(aDict)
jsonFile = open("data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()

Output

Run the above program, and data.json will be created in the working directory.

data.json

{"a": 54, "b": 87}

Example 2: Write JSON (List of Object) to File

In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json.

Python Program

import json

aList = [{"a":54, "b":87}, {"c":81, "d":63}, {"e":17, "f":39}]
jsonString = json.dumps(aList)
jsonFile = open("data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()

Output

Run the above program, and data.json will be created in the working directory.

data.json

[{"a": 54, "b": 87}, {"c": 81, "d": 63}, {"e": 17, "f": 39}]

Summary

In this tutorial of Python Examples, we learned how to write JSON to File, using step by step process and detailed example programs.