How To Write Json File In Python

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

In this tutorial, we’ll learn how to write JSON data to a file using Python. To achieve this, we’ll make use of the built-in json module that comes with Python. This module provides two methods for working with JSON data:

  • json.dump(): Serialize a Python object to a JSON formatted stream.
  • json.dumps(): Serialize a Python object to a JSON formatted string.

Writing JSON Data to a File

Suppose we have the following Python dictionary that we want to save as a JSON file:

    data = {
        "name": "John",
        "age": 30,
        "city": "New York"
    }
    

To write this dictionary to a JSON file, we can use the following code snippet:

    import json

    data = {
        "name": "John",
        "age": 30,
        "city": "New York"
    }

    # Writing JSON data to a file
    with open("data_file.json", "w") as write_file:
        json.dump(data, write_file)
    

In this example, we first import the json module. Next, we define the Python dictionary that we want to save as a JSON file. Then, we use the with statement to open a file named data_file.json in write mode. The with statement ensures that the file is properly closed after the JSON data is written to it.

Finally, we use the json.dump() method to write the JSON data to the file. The first parameter to this method is the Python object that needs to be converted to JSON, and the second parameter is the file object that the JSON data should be written to.

Conclusion

In this tutorial, we learned how to write JSON data to a file using the built-in json module in Python. The json.dump() method makes it very easy to serialize Python objects to JSON and save them to a file. Keep in mind that not all Python objects can be serialized to JSON; the json module can only handle basic data types like strings, numbers, lists, and dictionaries containing these data types.