How to Write JSON to File in Python?

The “JSON” or “JavaScript Object Notation” is a lightweight format for data exchange that can be read, written, and parsed by humans and machines. The “JSON” module provides different functions that can be used by importing the JSON module in the Python program. To write JSON to a file in Python, different functions of the “JSON” module, such as “json.dumps()” and “json.dump()” are used in Python.

To write JSON to a Python file, various methods are used in Python. This blog post demonstrates the following methods with appropriate examples:

Method 1: Using json.dumps() Function

The “json.dumps()” function is used to convert the Python object into json strings. In the example given below, the “json.dumps()” function is used to write the “JSON” to file with the help of the “open()” function:

Code:

import json
value = {"Name": "Lily", "Age": 21,"Height": 4.9}
with open("example.json", "w") as f:
    f.write(json.dumps(value))

In the above code:

  • The “JSON” module is imported, and the data is represented as a dictionary in the variable “dict_value”.
  • The “open()” function is used to create the JSON file with the name “example.json” and set the mode to “write-only ‘w’”.
  • The “json.dumps()” accept the dictionary variable and return the json strings. The JSON strings are then written to a file using the “f.write()” function.

Output:

The above output shows a JSON string successfully written into a file named “example.json”.

Method 2: Using json.dump() Function

The “json.dump()” function is also used along with “open()” function to write the JSON to a file. The “json.dump()” function writes a “JSON” object into a file-like object, but in contrast, the “json.dumps()” function returns a string object. In the below code, the “json.dump()” function is used to write the “JSON” to file:

Code:

import json
value = {"Name": "Lily", "Age": 21,"Height": 4.9,
              "Salary": "$100k"}
with open("example.json", "w") as f:
    json.dump(value, f, indent= 4)

In the above code:

  • The “open()” function creates the file and opens it as in “w” mode.
  • The “json.dump()” function is used to write Python objects into a file by taking the “value” as an argument.

Output:

The above output shows that the “JSON” data has been successfully written to a file named “example.json”.

Conclusion

To write JSON to a file, the “json.dumps()” and “json.dump()” functions are used along with the “open()” function in Python. The “open()” function creates the file and sets the “mode” parameter to “write-only”. This post discussed the methods to write JSON to file in Python.