How to Write a JSON File in Python

This post is lesson 45 of 54 in the subject Python Programming Language

Before reading this article, you should read How to Read a JSON File in Python to understand the basic concept of JSON and how to read a JSON file. With that knowledge, you will easily understand ways to write a JSON file in Python.

1. Convert dictionary to JSON in Python

We can convert a dictionary to a JSON string by using the json.dumps() function in the json module. When converting from a dictionary in Python to a JSON string, we will have Python objects converted to their corresponding data types in JSON. The table below summarizes the types of objects in Python that will be converted to the corresponding data type in JSON.

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull
import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}
print("type of data_dict:", type(data_dict))

#convert dictionary to json string
data_string = json.dumps(data_dict)

print("type of data_string:", type(data_string))
print(data_string)

Result

type of data_dict: <class 'dict'>
type of data_string: <class 'str'>
{"domainname": "gochocit.com", "active": true, "numberposts": 360, "category": ["hardware", "software", "network"], "facebookpage": "https://www.facebook.com/gochocit/", "build": {"language": "php", "cms": "wordpress", "database": "mysql"}}

1.1. Print JSON string with indentation

In the example above, the JSON string is printed without indentation, which is hard to read. We can print the JSON string with indentation by passing a value to the indent parameter of the json.dumps() function.

import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

#convert dictionary to json string with indentation
data_string = json.dumps(data_dict, indent=4)
print(data_string)

Result

{
    "domainname": "gochocit.com",
    "active": true,
    "numberposts": 360,
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

1.2. Sort JSON string with the key in JSON

We can sort the key in JSON in alphabetical order when printed out. To do this, we pass the value True to the sort_keys parameter of the json.dumps() function.

import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

#convert dictionary to json string with sort_keys
data_string = json.dumps(data_dict, sort_keys=True)
print(data_string)

Result

{"active": true, "build": {"cms": "wordpress", "database": "mysql", "language": "php"}, "category": ["hardware", "software", "network"], "domainname": "gochocit.com", "facebookpage": "https://www.facebook.com/gochocit/", "numberposts": 360}

1.3. JSON string with sort and indentation in Python

When we want to create a JSON string with sort and indentation, we pass values to both parameters.

import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

#convert dictionary to json string with sort_keys and indent
data_string = json.dumps(data_dict, sort_keys=True, indent=4)
print(data_string)

Result

{
    "active": true,
    "build": {
        "cms": "wordpress",
        "database": "mysql",
        "language": "php"
    },
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "domainname": "gochocit.com",
    "facebookpage": "https://www.facebook.com/gochocit/",
    "numberposts": 360
}

2. Write JSON file in Python

Once we have created a JSON string, it is very easy to write the JSON data to a file. This is similar to writing a file in Python.

import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

#convert dictionary to json string with sort_keys and indent
data_string = json.dumps(data_dict, sort_keys=True, indent=4)

# write json string to file
myjsonfile = open("info2.json", "w")
myjsonfile.write(data_string)
myjsonfile.close()

Result of the content of the created file info2.json

{
    "active": true,
    "build": {
        "cms": "wordpress",
        "database": "mysql",
        "language": "php"
    },
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "domainname": "gochocit.com",
    "facebookpage": "https://www.facebook.com/gochocit/",
    "numberposts": 360
}

If we want to create a JSON string from an object in Python and write the JSON string to a file with only two lines of code, we can use the json.dump() function.

import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

# write json string to file
with open("info2.json", 'w') as file:
    json.dump(data_dict, file, sort_keys=True, indent=4)
file.close()

Result of the content of the created file info2.json

{
    "active": true,
    "build": {
        "cms": "wordpress",
        "database": "mysql",
        "language": "php"
    },
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "domainname": "gochocit.com",
    "facebookpage": "https://www.facebook.com/gochocit/",
    "numberposts": 360
}
5/5 - (1 vote)
Previous and next lesson in subject<< How to Read a JSON File in PythonConvert XML to JSON in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *