Python: Converting Dictionary to JSON string

In this tutorial we will check how to serialize a Python dictionary to a JSON string.

Introduction

In this tutorial we will check how to serialize a Python dictionary to a JSON string.

This tutorial was tested with Python version 3.7.2.

The code

We will start the code by importing the json module. This module will expose to us the function that allows to serialize a dictionary into a JSON string.

import json

After this we will define a variable that will contain a Python dictionary. We will add some arbitrary key-value pairs that could represent a person data structure, just for illustration purposes.

person = {
  "name": "John",
  "age": 10,
  "skills": ["Cooking", "Singing"]
}

To serialize the dictionary to a string, we simply need to call the dumps function and pass as input our dictionary. Note that this function has a lot of optional parameters but the only mandatory one is the object that we want to serialize.

We are going to print the result directly to the prompt.

print(json.dumps(person))

Note that if we don’t specify any additional input for the dumps function, the returned JSON string will be in a compact format, without newlines.

So, we can make use of the indent parameter by passing a positive integer. By doing this, the JSON string returned will be pretty printed with a number of indents per level equal to the number we have passed.

We will pass an indent value of 2.

print(json.dumps(person, indent = 2))
print("------------\n\n")

To finalize, we will check another additional parameter called sort_keys. This parameter defaults to False but if we set it to True the keys will be ordered in the JSON string returned.

print(json.dumps(person, sort_keys = True))

The final code can be seen below.

import json

person = {
  "name": "John",
  "age": 10,
  "skills": ["Cooking", "Singing"]
}

print(json.dumps(person))
print("------------\n\n")

print(json.dumps(person, indent = 2))
print("------------\n\n")

print(json.dumps(person, sort_keys = True))

Testing the code

To test the code, simply run it in a tool of your choice. I’ll be using IDLE, a Python IDE.

You should get an output similar to figure 1. In the first print we can see that the dictionary was correctly converted to a compact JSON string, as expected.

In the second print we can see a prettified version of the JSON with the 2 indents that we specified in the code.

In the third print we can confirm that the keys were ordered.

Figure 1 – Output of the program.

References

[1] https://docs.python.org/3/library/json.html

Leave a Reply