Kodeclik Blog

Converting a Python dictionary into JSON

Assume we have a Python dictionary like so:
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.

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():
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:
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:
The output for these two print lines will look like:
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:
and the output will be:
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:
The output will be:
providing a much nicer output to inspect. Finally, you can use the sort_keys=True option like so:
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:

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:
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:
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.

Join our mailing list

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

Copyright @ Kodeclik 2024. All rights reserved.