Python – Write JSON to a File

Learn to write JSON data into an existing file using json.dump() method. Also, learn to apply sorting and formatting to the JSON written into the file.

For quick reference, below is the code which writes a JSON dictionary object to a “users.json” file.

import json

# Python object
py_dict = {
	"id" : 1
}

# Write to File
with open('users.json', 'w') as json_file:
	json.dump(py_dict, json_file, indent=4,  sort_keys=True, separators=(',',':'))

1. json.dump() Method

The json.dump() serializes a Python object as a JSON formatted stream into a given file.

1.1. Method Parameters

dump(obj, fp, *, skipkeys=False, 
		check_circular=True, allow_nan=True,  
		indent=None, separators=None, default=None, 
		sort_keys=False, **kw)

Except obj and fp, others are optional parameters.

  • obj : to be serialized as a JSON formatted stream.
  • fp : The file object where Json data will be written.
  • skipkeys (default: False) : dict keys that are not of a basic type will be skipped. Otherwise it will raise TypeError.
  • check_circular (default: True) : circular reference check for container types. May result in result in an OverflowError.
  • allow_nan (default: True) : if false, it will be a ValueError to serialize out of range float values. By deafult, JavaScript equivalents (NaN, Infinity, -Infinity) are used.
  • indent : used for pretty-printing with given indent level.
  • separators : separators used in the JSON.
  • default : a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
  • sort_keys (default: False) : if true then the output of dictionaries will be sorted by key.

1.2. Conversion Rules

The dump() method uses below given conversion rules while converting a python object to JSON data.

Python JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null

2. Python Write JSON to File Examples

Example 1: Writing Python Dict to File

In given example, we are writing a python dict object to a file.

import json

# Python dict
py_dictionary = {
    "Name": "Lokesh",
    "Age": 39,
    "Blog": "howtodoinjava"
}

# Write to File
with open('users.json', 'w') as json_file:
  json.dump(py_dictionary, json_file)

Program output.

{"Name": "Lokesh", "Age": 39, "Blog": "howtodoinjava"}

Example 2: Write Pretty Printed JSON to File in Python

For pretty printing, use indent parameter of the method dump().

import json

# Python dict
py_dictionary = {
    "Name": "Lokesh",
    "Age": 39,
    "Blog": "howtodoinjava"
}

# Write to File
with open('users.json', 'w') as json_file:
  json.dump(py_dictionary, json_file, indent=4)

Program output.

{
    "Name": "Lokesh",
    "Age": 39,
    "Blog": "howtodoinjava"
}

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode