Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

Converting a Python dictionary into JSON

Assume we have a Python dictionary like so:

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}

Lets convert this dictionary into a JSON format. But first, why would you need to do that? JSON stands for JavaScript Object Notation. It is an open-standard file format for data interchange on the web, especially between web applications and servers. It's designed for human-readable data exchange and can be used with most programming languages, such as Python, Java, PHP, Ruby, and more. It also helps developers store data in an organized manner. So JSON is a universal data format that you will encounter in your coding journey.

Python save dictionary to JSON

Method 1: Use the json.dumps() method

One way to convert a dictionary to JSON is to import the json library into your Python program and use the json module's dumps() function to convert your dictionary into valid JSON which is stored in a string variable. This function takes two parameters; the first is the dictionary you want to convert and the second is an optional parameter known as indent which specifies how many spaces should be used when formatting your output string. You can also use sort_keys=True if you would like your output string to be sorted alphabetically by key name. Lets try all these options out!

Here is a very basic program that explores json.dumps():

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}

serialized_calendar = json.dumps(calendar) 
print(serialized_calendar)
print(calendar)

Here the original dictionary is stored in the “calendar” variable and the json-converted one is stored in the “serialized_calendar” variable. The output is:

{"January": 31, "February": 28, "March": 31, "April": 30, "May": 31, 
"June": 30, "July": 31, "August": 31, "September": 30, "October": 31, 
"November": 30, "December": 31}
{'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 
'June': 30, 'July': 31, 'August': 31, 'September': 30, 'October': 31, 
'November': 30, 'December': 31}

Looks like it worked - but we don’t quite notice any differences (other than the single quotes vs double quotes). How do we know that the conversion worked correctly? Add these two lines to the end of your program:

print(serialized_calendar[0])
print(calendar[0])

The output for these two print lines will look like:

{
Traceback (most recent call last):
  File "main.py", line 20, in <module>
    print(calendar[0])
KeyError: 0

Note that the serialized_calendar variable is a string and thus the very first character is the curly brace. But the calendar variable is really a dictionary (an associative array) so when you ask for calendar[0], the print command looks for an entry in the dictionary with key equal to zero and of course there is no such key. This should reassure you that the types of these variables are different.

Here is another way to convince yourself that these variables are different. Try these two lines:

print(type(calendar))
print(type(serialized_calendar))

and the output will be:

<class 'dict'>
<class 'str'>

confirming that the dict variable (calendar) has been converted to a string variable (serialized_calendar).

The other options you can try are to use the indent parameter:

import json

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}

serialized_calendar = json.dumps(calendar,indent=3) 
print(serialized_calendar)

The output will be:

{
  "January": 31,
  "February": 28,
  "March": 31,
  "April": 30,
  "May": 31,
  "June": 30,
  "July": 31,
  "August": 31,
  "September": 30,
  "October": 31,
  "November": 30,
  "December": 31
}

providing a much nicer output to inspect. Finally, you can use the sort_keys=True option like so:

import json

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}

serialized_calendar = json.dumps(calendar,indent=3,sort_keys=True) 
print(serialized_calendar)

This program does what you think it does. The serialized_calendar (recall it is a string variable) sorts the dictionary by its keys before storing it:

{
  "April": 30,
  "August": 31,
  "December": 31,
  "February": 28,
  "January": 31,
  "July": 31,
  "June": 30,
  "March": 31,
  "May": 31,
  "November": 30,
  "October": 31,
  "September": 30
}

Method 2: Use the json.dump() method

The second approach to converting a Python dictionary to JSON is to use the json.dump() function (note there is no “s” in the dump). This function does the same things as json.dump() but is used to write the JSON to a file rather than store it in a string. We will provide just one example with the latest arguments we used with json.dumps() but other examples will work similarly:

import json

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}

with open("dict.txt", "w") as f:
    json.dump(calendar, f, indent=3, sort_keys=True)

If you run this program, there will not be any output (because we do not have any print statements). Instead there will be a file called “dict.txt” created and if you open that file the output will be what we expected:

{
  "April": 30,
  "August": 31,
  "December": 31,
  "February": 28,
  "January": 31,
  "July": 31,
  "June": 30,
  "March": 31,
  "May": 31,
  "November": 30,
  "October": 31,
  "September": 30
}

In conclusion, converting a Python dictionary into valid JSON strings is relatively easy and straightforward using just one line of code from the json module! Simply import json in your script or project and then use its dumps() function or dump() function. This makes it ideal for web developers who need to quickly transfer data between applications or send data back and forth between server and client parts of an application. Plus, since there are several libraries out there that help with working with large amounts of complex data (like pandas) in JSON format so this is a very useful to have for a lot of situations!

If you liked this blogpost, checkout how to unpack a Python dictionary to variables.

For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.