Save Python dict as JSON: Convert Dictionary to JSON

In this article, we will learn how to save a dictionary as JSON in python.

While programming we need to work with lots of data. To store such data we use different formats, and one of the formats is the JSON format.

The JSON format is used mostly in all programming languages and it is a very well-structured way to store data in our programs.

In python, we use a similar data structure called the dictionary to store data for our programs.

Let’s understand how we can save the data in a python dictionary as a JSON object in this post.

What is JSON in python?

JSON (JavaScript Object Notation) is an open data-interchange format that is used to store data in a human-readable format.

Since it is a very well-structured format, it is used in many programming languages and it’s easy to exchange data between a web application and a server using JSON.

It stores the data in a key value pair inside curly brackets ({}). It looks exactly same as python dictionary structure with some differences.

Example of JSON format:

{
  "firstName": "John",
  "lastName": "Smith",
  "age": 27,
}

In JSON the key is inside a double quotation mark (" ") but the values can be any data type, for example, string, integers, array, and objects.

Convert Dictionary to JSON in Python

There are different ways to convert a dictionary into a JSON object using python. Let’s check some methods with code examples.

Using dumps() function to save dict as JSON

To save a dictionary as json object we can use the in-built dumps() function in python. We can use the function by importing the in-built json module in our program.

The json module helps to parse JSON strings and files that contain the JSON object.

The json.dumps() function converts a dictionary into a string object.

Example:

import json

my_dict = {
  'firstName': 'Alex',
  'lastName': 'Johns',
  'company': 'Facebook',
  'id': 1234
}
json_obj = json.dumps(my_dict)
print(json_obj)

Output:

{"firstName": "Alex", "lastName": "Johns", "company": "Facebook", "id": 1234}

Here, we have defined a dictionary named my_dict and then used json.dumps() function to convert it into a JSON object.

Convert a nested dictionary into a JSON object

If you have a nested dictionary then it will be hard to read the data if we just convert it to a JSON object. Therefore, to pretty print the data in the dictionary as a JSON object we can use the json.dumps() function and pass the indent option as a parameter.

The indent is a non-negative number that is used to print or display the JSON object element with proper spacing and indentation. It pretty-prints the elements of the JSON object.

Example:

import json

my_dict = {
  'john':{
        'firstName':'John',
        'LastName': 'Wick'
    },
    'tom':{
        'firstName':'Tom',
        'LastName': 'Cruise'
    }
}
json_obj = json.dumps(my_dict, indent= 3)
print(json_obj)

Output:

{
   "john": {
      "firstName": "John",
      "LastName": "Wick"
   },
   "tom": {
      "firstName": "Tom",
      "LastName": "Cruise"
   }
}

Here, indent=3 means the spaces we want at the beginning of each object element.

Convert dict to JSON using sort_keys

Let’s say we want to save the python dictionary as a JSON object and sort the key in order. To do that we can use the dumps() and pass on the sort_keys parameter.

The sort_keys takes a boolean value, and if it is set to True, it sorts json dump by its keys.

Example:

import json

my_dict = {
    'name':'John',    
    'adddress':'New York',
    'bio': 'Engineer'
}
json_obj = json.dumps(my_dict, sort_keys=True)
print(json_obj)

Output:

{"adddress": "New York", "bio": "Engineer", "name": "John"}

As you can see, the sort_keys sorts the keys of the dictionary and convert it into a json object.

Convert Python dictionary to JSON File

Let’s say we have a python dictionary with some data in it. And we want to convert it to a JSON object and save it in a new json file.

So to achieve that we have to use both json.dumps() function and the file.write() function in our python program.

Example:

import json

my_dict = {
    'name':'John',    
    'adddress':'New York',
    'bio': 'Engineer'
}
json_obj = json.dumps(my_dict)

json_file =  open("data.json", "w")
json_file.write(json_obj)
json_file.close()

When we run this program, it will create a data.json file with the converted json object in it.

In the data.json file:

{"name": "John", "adddress": "New York", "bio": "Engineer"}

Here, in the above example, we have converted the dict into a JSON object using json.dumps() function.

Next, we have created a file name data.json using open(filename, 'w') function and wrote the JSON content into it using the file.write() function.

In the end, we close the file using close() function.

Conclusion:

In this article, we have learned ways to convert a python dictionary into a JSON object using the dumps() function and also learned how to sort the keys while converting, and also how to save dictionary data as JSON in a new json file.


Other Articles You’ll Also Like:

Merge multiple JSON objects into one single object in Python

Scroll to Top