JSON file formats are used extensively for data transmission. This article will discuss how we can convert a python dictionary to JSON format.
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.
In this example, we first opened a json file using the open()
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 close()
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 Address
. When we try to convert the dictionary containing the object of type Address
to JSON, the dumps()
method doesn’t know how to convert the Address
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!
Recommended Python Training
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.