You are currently viewing Python Write JSON Data to a File?

How do I write JSON data to a file in Python? You can easily write JSON data to a file using the built-in Python json module. To write JSON data to a file use the json.dump() method. Besides this method, there are more methods as well which we will discuss in this article along with examples.

Advertisements

Related: Python json dumps() Function with Examples

1. Quick Examples of Writing JSON data to a File

These are some quick examples to give you a high-level idea of how to wirte a JSON data to a file and we will discuss each of these methods in detail later on.


# Quick Examples of Writing JSON data to a File

# Import
import json

# Write dictionary to file using json.dump()
file_path = "data.json"
with open(file_path, "w") as f:
    json.dump(data, f)

# Write JSON data with Unicode characters to file
file_path = "unicode_data.json"
with open(file_path, "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False)

2. What is JSON Data?

JSON (JavaScript Object Notation) is a format used to represent data in a way that is easy for both humans and machines to understand. It is commonly used to transmit data between web applications and servers. JSON is based on a subset of the JavaScript programming language, so if you’re familiar with JavaScript, you’ll find JSON easy to understand.

In JSON, data is represented using a simple key-value pair structure. The keys represent the names of fields or attributes of the data, while the values represent the actual data itself. JSON data can be represented as a string and can be easily converted to a Python dictionary or list using the built-in json module.

Below is a sample JSON. We will use this JSON throughout our examples:


json_data = {
    "name": "Python",
    "year": 1991,
    "creator": "Guido van Rossum",
    "popular": True
}

3. Using json.dump() to Write JSON Data to a File

The json.dump() method is used to write JSON data to a file in Python. It takes two arguments, the data to be written, and the file object to write to.

Following is the syntax of the json.dump() method.


# Import json module
import json

# Write data to object file
json.dump(data, file_object)

Here,

  • data – Any object with JSON data
  • file_object – File object where to write JSON data

3.1 Write Data to JSON File

Let’s see an example of writing a Python object to a JSON file. The data parameter represents the JSON data to be written to the file. This can be any Python object that is JSON serializable, such as a dictionary or a list. Here, in the below example json_data is a dictionary object which I will write to a file. Alternatively, you can also put this data to a file and read json from a file into a object.

See the below example:


# Import json module
import json

# Create dictionary object which is json representation
json_data = {
    "name": "Python",
    "year": 1991,
    "creator": "Guido van Rossum",
    "popular": True
}

# Writing JSON data to a file using a file object
with open("data.json", "w") as outfile:
    # json_data refers to the above JSON
    json.dump(json_data, outfile)

Though this is the simplest way to write JSON data to a file. However, there is more to this method. There are more parameters of this method. Below is the complete syntax of the json.dump() function:


# json.dump() Syntax
json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, 
    check_circular=True, allow_nan=True, cls=None, indent=None, 
    separators=None, default=None, sort_keys=False, **kw
)

We have seen only two required parameters of this method, however, we can always use those optional parameters when necessary. Let’s see a few of them right here.

3.2 skipkeys Parameter of json.dump()

The skipkeys parameter is a boolean value that determines whether keys that are not JSON serializable should be skipped (True) or raise a TypeError (False). The default value is False.

Let’s make the skipkeys value True and see the result.


import json

data ={
    "name": "Python",
    (1, 2): 1991,
    "creator": "Guido van Rossum",
    "popular": True
}

# Example with skipkeys=True
with open("data.json", "w") as outfile:
    json.dump(data, outfile, skipkeys=True)

Yields the below output, because the JSON object is not serializable.


# Output:
raise TypeError(f'keys must be str, int, float, bool or None, '
TypeError: keys must be str, int, float, bool or None, not tuple

3.3 “ensure_ascii” Paramter of json.dump()

The ensure_ascii parameter is a boolean value that determines whether non-ASCII characters should be escaped (False) or represented as ASCII characters (True). The default value is True.


import json

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

# Example with ensure_ascii=True (default)
with open("data.json", "w") as outfile:
    json.dump(data, outfile)

Remaining of the parameters are also adding other functionality which you can try. Below are one-line explanation of each of the parameters.

  1. check_circular: A Boolean value specifying whether to check for circular references in the Python object. Default is True.
  2. allow_nan: A Boolean value specifying whether to allow NaN, Infinity, and -Infinity values. The default is True.
  3. cls: A custom encoder class used to convert non-JSON serializable objects into JSON serializable objects.
  4. indent: An integer value representing the number of spaces used for indentation. If None, the output JSON will be compact.

4. json.dumps() – Output JSON to a File

The json.dumps() function is very much similar to Python json.dump() function which can also be used to write to a JSON file. However, json.dumps() is a method to serialize Python objects to a JSON formatted string, not to write JSON data to a file. We can use this method in combination with the write() method of a file object to write the JSON formatted string to a file.

Related: How to write a file in Python?

See the below example:


import json

# Serialize the Python object to a JSON formatted string
json_data = json.dumps(data)

# Write the JSON formatted string to a file
file_path = "example.json"
with open(file_path, "w") as outfile:
    outfile.write(json_data)

5. Write JSON having UNICODE to a File

When you write JSON data that contains Unicode characters to a file using Python’s built-in json.dump(), by default, the Unicode characters will be escaped. You can use the codecs.open() method to open the file with the specified encoding and then write the JSON data to the file as a string.


import codecs, json

# Write the dictionary to a file with Unicode characters
file_path = "data.json"
with codecs.open(file_path, "w", encoding="utf-8") as f:
    f.write(json.dumps(data, sort_keys=True, ensure_ascii=False))

6. Summary and Conclusion

In this article, you have learned how to write JSON data to a file in Python. We have discussed different methods with examples. I hope this article was helpful. If you have any questions, you can ask them in the comment section below.

Happy Coding!