Skip to main content
Convert Python Dictionary To JSON

Convert Python Dictionary To JSON

This python tutorial help to convert Python Dictionary To JSON. The JSON is a very popular format to exchange data between server and client.

The Python dictionary is a collection that is unordered, changeable, and indexed. We will convert dict collection in JSON format.

How To Convert Dict to JSON

We will take a simple dict and store a string key:value pair. We will store employee data in dict object.

What is Python Dictionary

The python Dictionary is an unordered collection of data values, that store the data values like a map. The dictionary holds key:value pair.

The key can behold only a single value as an element. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples.

Dict = {"name": 'Izhaan', "salary": 1234, "age": 23} 
print("\nDictionary with the use of string Keys: ") 
print(Dict)

Python has a JSON package to handle and process JSON data. The process of encoding the JSON is usually called serialization.

You can also checkout other python tutorials:

Deserialization is a reciprocal process of decoding data that has been stored or delivered in the JSON standard. The json.dumps() method is used to convert dict to JSON string.

import json

empDict = {
    "name": 'Izhaan', 
    "salary": 1234, 
    "age": 23
} 
emp_json = json.dumps(empDict)
print(emp_json)

We have defined one empDict dictionary and then convert that dictionary to JSON using json.dumps() method. This method also accepts sort_keys as the second argument to json_dumps(). This helps to sort the dictionary against keys.

import json

empDict = {
    "name": 'Izhaan', 
    "salary": 1234, 
    "age": 23
} 
emp_json = json.dumps(empDict, sort_keys=True)
print(emp_json)

Leave a Reply

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