How To Convert Python Dictionary To JSON

In this tutorial, we will learn how to convert Python dictionary to JSON object i.e JavaScript Object Notation.

We can convert Python objects to equivalent JSON objects i.e Python list and tuple are equivalent to JSON array, Python int and float are equivalent to JSON number, Python str is equivalent to JSON String, Python Dictionary is equivalent to JSON String.

Python Dictionary To JSON String

The first thing we need to do is to import the ‘json’ library as shown below.

import json

The ‘json’ library has a method ‘dumps’ that converts the Python dictionary to the JSON object.

import json
my_dict={'website':'codespeedy','topic':'json and python','year':2019,'list':[10,20,30]}
json_string=json.dumps(my_dict)
print (json_string)

Output:

{"website": "codespeedy", "topic": "json and python", "year": 2019, "list": [10, 20, 30]}

In the above code, we first have declared a python dictionary my_dict and then have converted it into JSON String using dumps method and have stored the result in json_string.

We can use the ‘indent’ attribute for indentation to make it easier for reading.

import json
my_dict={'website':'codespeedy','topic':'json and python','year':2019,'list':[10,20,30]}
json_string=json.dumps(my_dict,indent=3)
print (json_string)

Output:

{
    "website": "codespeedy",
    "topic": "json and python",
    "year": 2019,
    "list": [
        10,
        20,
        30
    ]
}

We can use the ‘sort_keys’ attribute to sort the dictionary elements with respect to keys.

import json
my_dict={'website':'codespeedy','topic':'json and python','year':2019,'list':[10,20,30]}
json_string=json.dumps(my_dict,indent=3,sort_keys=True)
print (json_string)

Output:

{
    "list": [
        10,
        20,
        30
    ],
    "topic": "json and python",
    "website": "codespeedy",
    "year": 2019
}

If you want to learn how to parse JSON see the post- How to parse JSON in python.

You may also read

Leave a Reply

Your email address will not be published. Required fields are marked *