Convert Dictionary To JSON

PUBLISHED ON JANUARY 3, 2020

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

The python dictionary is a collection which is unordered, changeable and indexed.We will convert dict collection in json format.

How To Convert Dict to JSON

We will take simple dict and stored string key:value pair.We will stored employee data into 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 be hold only single value as an element.Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples.HTML

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

The python has json package to handle and process json data.The process of encoding the JSON is usually called the serialization.The 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.HTML

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 accept sort_keys as the second argument to json_dumps().This help to sort the dictionary against keys.HTML

import json

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

Reference : https://www.pythonpip.com/python-tutorials/convert-python-dictionary-to-json/

Last updated