How to convert a dictionary to JSON file in Python?

JSON file formats are used extensively for data transmission. This article will discuss how we can convert a python dictionary to JSON format.

Table of Contents

What is JSON Format?

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data format. It is easy for humans to read and write and for machines to parse and generate. JSON is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. It is commonly used for exchanging data between a client and a server or between applications.

The data in JSON format is represented as key-value pairs, where the keys are strings and the values can be either strings, numbers, arrays, or other JSON objects. JSON uses a comma-separated list of key-value pairs to represent objects, and square brackets to represent arrays. The data is enclosed in curly braces just like a python dictionary.

Convert Python Dictionary to JSON String

We will use the dumps() method defined in the json module to convert a dictionary to a JSON string. I have discussed the syntax of the dumps() method in this article on working with json files in python. The dumps() method takes the dictionary as its input argument and returns the json string as shown below.

import json
myDict = {
    "name": {
        "first": "John",
        "last": "Doe"
    },
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zipcode": "12345"
    },
    "email": "[email protected]",
    "age": 32
}
print("The dictionary is:")
print(myDict)
json_string=json.dumps(myDict)
print("The JSON string is:")
print(json_string)

Output:

The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}

In the above example, we have passed a python dictionary to the dumps()method. After execution, it returns a JSON string. Observe that the structure of the dictionary and the JSON object are almost the same.

Dictionary to JSON File in Python

To convert a dictionary to a JSON file, we can use the dump() method. The dump() method takes the python dictionary as its first input argument and a file pointer to the destination JSON file as its second input argument. After execution, it saves the dictionary into a JSON file as shown in the following example.

import json
myDict = {
    "name": {
        "first": "John",
        "last": "Doe"
    },
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zipcode": "12345"
    },
    "email": "[email protected]",
    "age": 32
}
file=open("person_data.json","w")
json.dump(myDict,file)
file.close()

Output:

The file looks as follows.

JSON File created from a python dictionary

In this example, we first opened a json file using the

The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
1 method in write mode. Then, we used the dump() method to write the dictionary to the json file. Finally, we closed the file using the
The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
3 method.

Error While Converting Dictionary to JSON Format

If the python dictionary contains elements other than the primitive data types and container objects such as lists, the above approaches won’t work. For instance, consider the following example.

import json
class Address:
    def __init__(self,street,city,state,zipcode):
        self.street=street
        self.city=city
        self.state=state
        self.zipcode=zipcode
myAddress=Address("123 Main St","Anytown","CA","12345")
myDict = {
    "name": {
        "first": "John",
        "last": "Doe"
    },
    "address": myAddress,
    "email": "[email protected]",
    "age": 32
}
print("The dictionary is:")
print(myDict)
json_string=json.dumps(myDict)
print("The JSON string is:")
print(json_string)

Output:

The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': <__main__.Address object at 0x7fc6544fd9c0>, 'email': '[email protected]', 'age': 32}
TypeError: Object of type Address is not JSON serializable

In this example, we have created a user-defined object of class

The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
4. When we try to convert the dictionary containing the object of type
The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
4 to JSON, the dumps() method doesn’t know how to convert the
The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
4 object to JSON. Hence, it raises a python TypeError exception.

To avoid this error, you can direct the dump() or dumps() method to convert custom python objects into json files. For this, you can read this article on custom json encoder in python.

Conclusion

In this article, we have discussed ways to convert a dictionary to a JSON string or file in python. 

To learn more about python programming, you can read this article on how to create a chat app in Python. You might also like this article on linear regression using the sklearn module in Python.

Stay tuned for more informed articles.

Happy Learning!

Related

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

How to convert a dictionary to a JSON file in Python?

In python, we have an inbuilt module called 'JSON' which has an in-built function called dumps(). The dumps() function is used to convert dict to JSON python. We can do this by simply importing the "JSON" module which helps to easily parse the JSON strings that contain the JSON object.

How to convert list of dictionary to JSON in Python?

dumps() This function will convert a list of dictionaries to JSON. Parameters: dictionary – name of a dictionary which should be converted to JSON object.

How to convert a dictionary to a JSON string?

To Convert dictionary to JSON you can use the json. dumps() which converts a dictionary to str object, not a json(dict) object! so you have to load your str into a dict to use it by using json. loads() method.