Different Ways To Convert Dictionary To JSON In Python

dictionary to Json

If you are a programmer who usually codes in the Python programming language, did you ever convert a Dictionary to JSON in Python? Do you know why it is needed to convert a Dictionary to JSON? In your programming journey, you might have done this or might not. But, if you are the one who recently started the journey in the Python programming language, you must read this article. Because I am going to show you the various ways of converting a Python Dictionary to JSON. So, this article is very important to the one who is a beginner in Python programming language.

Before going to know the ways of converting a Dictionary to JSON in Python, it is important to know what a Dictionary is and what means JSON in Python? And it is also important to know why we convert a dictionary to JSON. Hence, the primary thing you have to do is to know the definition of Dictionary and JSON in python and then you need to know the reason for converting a Dictionary into JSON.

Dictionary in Python

Python’s dictionaries are similar to the hash table. The dictionaries in python work with key-value pairs with associative arrays. These dictionary keys are usually numbers or strings. However, they can be of any Python type. You will store data values in these key value pairs in Python. Hence, you can also call them as maps, hashmaps, hash tables, and associative arrays.

In general, a dictionary is defined as a collection of ordered*and changeable values that allow duplicates. You will also find this concept of a key-value store in various computing systems, such as caches and high-performance databases. They use this concept widely in their mechanisms.

Using dictionaries is important because they improve the readability of your code. Dictionaries play an important role in Python because they carry the task of writing out Python dictionary keys along with values adding a layer of documentation to the code. You can easily debug a code if it is more streamlined.

A dictionary can be defined by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:). Here, you need to separate each key from the value associated with it. Let us see the syntax of the Dictionary in Python.

Syntax of the dictionary in the Python programming language will be as follows:

Syntax:

dictionary = {

    <key>: <value>,

    <key>: <value>,

      .

      .

      .

    <key>: <value>

}

Now, let us look at an example of a dictionary in Python so that you will understand it in a clear way.

The following is an example for Python Dictionary:

Example-1:

Exampledict1 = {

    ‘first_name’: ‘Arun’,

    ‘last_name’: ‘Sai’,

    ‘age’: 21,

    ‘favorite_colors’: [‘blue’, ‘green’],

    ‘active’: True

}

for key in person.keys():

    print(key)

For the above program of python dictionary, you will get the following output:

Output;

first_name

last_name

age

favorite_colors

active

Let us see another example.

Example-2:

Exampledict2 = {

    ‘first_name’: ‘Arun’,

    ‘last_name’: ‘Sai’,

    ‘age’: 21,

    ‘favorite_colors’: [‘blue’, ‘green’],

    ‘active’: True

}

for key in person.keys():

    print(value)

For the above program of python dictionary, you will get the following output:

Output;

Arun

Sai

21

[‘blue’, ‘green’]

True

This is how a dictionary works in the Python programming language. Now, let us go to the working of a JSON in Python. Here, you will know the definition of JSON in python, how it works, and its uses in Python.

JSON in Python

JSON is expanded as JavaScript Object Notation (JSON). It is a standard text-based format in Python. Using JSON, you can represent structured data based on JavaScript object syntax. Many people mostly use this commonly to transmit data in web applications. You can use this to send some data from the server to the client. You can also display this on a web page, or vice versa. Using the syntax of JSON, you can also store and exchange the data.

This is the representation of JavaScript objects such as literals, arrays, and scalar data that is relatively easy to read and write. Most people use this for serializing structured data and exchanging it over a network usually between a server and web applications. You must import the JSON package to use this feature in the Python script. The text in JSON is done through quoted-string as it contains the value in key-value mapping within { }.

Java Script Object Notation (JSON) is most similar to python dictionaries but it is a lightweight data format. You need to use the open() function to create a JSON file in Python in which the file name and mode will be taken by the open() function as an argument. This will be created only if the file is not there, otherwise, it will not be created.

To create a JSON file in Python, you need to follow the below procedure that is mandatory:
  1. The first thing you need to do is to create a JSON file in python using the open() function. Consider the following example:

Example:

import json

with open(‘new_file.json’, ‘w’) as f:

    print(“Create a JSON file”)

  • Now, Create a json file from the existing json file in Python. For this, you first need to open the existing file in reading mode which will read the content of that file. Now, you have to use the open() and with statement in write mode to dump the json data to a new json file. Consider the following example:

Example:

{

  “data”: [

    {

      “name”: “arun”,

      “age”: “#21”

    },

    {

      “name”: “sai”,

      “age”: “#20”

    },

    {

      “name”: “yuva”,

      “age”: “#22”

    },

    {

      “name”: “Bharath”,

      “age”: “#19”

    }

  ]

}

  • Then the next step is to create a new json file from this data.json file. Consider the following example:

Example:

import json

with open(‘data.json’) as f:

    data = json.load(f)

with open(‘new_file.json’, ‘w’) as f:

    json.dump(data, f, indent=2)

    print(“Here, a New json file is created from data.json file”)

This is all about a JSON in python. With this, I hope you got an idea about a Dictionary and JSON in Python. Now, you are going to know about the different ways to convert a Dictionary to JSON in Python.

1) Method-1:

In this method, you will convert the Dictionary to JSON in Python using the dumps() function with indentation. Usually, the dumps() method has one mandatory parameter through which it can take the dictionary object to convert the data into JSON string. Let us see an example of that. Consider the following example:

Example-1:

import json

dictExample= { “student_id”: “190340059”, “name”: “Arunsai”, “batch”: 30, “semester”:6 }

print(“Dictonary: \n”, dictExample, “\n”)

jsonExample= json.dumps(dictExample)

print(“JSON without indentation: \n”,jsonExample, “\n”)

jsonExample= json.dumps(dictExample,indent=3)

print(“JSON with indentation: \n”, jsonExample)

In the above example program, consider dictExample as a dictionary variable. It has the data of a particular student record. In the first step, the dumps() method is used with one argument and the value of dictExample is converted into JSON data. Both dictionary and JSON format will have the same output if no indentation is used in JSON data. Now, you will use the dumps() method with two arguments.

2) Method-2:

In the second method, you will be able to convert the dictionary into JSON using dumps() using sort_keys. You can sort the keys of JSON data by using the sort_keys argument of dumps(). However, you will get the default value of this argument is False. Let us see an example of that. Consider the following example:

Example-2:

import json

dictExample = {‘name’:’Arunsai’,’Month’:’June’,’year’:2022,’sales’:[100, 210, 350, 120]}

print(“Dictonary Output: \n”, dictExample”\n”)

jsonExample= json.dumps(dictExample,indent = 5)

print(“JSON with indentation: \n”, jsonExample)

jsonExample = json.dumps(dictExample,indent = 5, sort_keys = True)

print(“Sorted JSON with indentation: \n”, jsonExample)

In the above example program, you can convert the dictionary object into JSON data without using sort_keys. You don’t even need to use sort_keys to display the use of this argument. But, you will use the first dumps() method with indent value 5 to show the output JSON data using indentation 5. In the second dumps() method, you will use the sort_keys and set to True for sorting the key values. The data after sorting key values will be shown in the last JSON output.

3) Method-3:

In this method, you will be able to convert the dictionary to JSON data and store it into a JSON file. You can be able to store the JSON data into a file after converting from the dictionary by using the dump() method. Let us see an example of that. Consider the following example:

Example-3:

import json

dictExample = { ‘c-101’: ‘PHP Programming’, ‘c-102’: ‘Bash Programming’, ‘c-103’:

‘Python Programming’,

  ‘c-104’: ‘Object Oriented Programming’ }

print(“Dictionary Output: \n”, dictExample, “\n”)

jsonFile = ‘course_list.json’

with open(jsonFile, ‘w’) as fileHandler1:

  json.dump(dictExample, fileHandler1, indent = 2)

fileHandler2 = open(jsonFile)

print(“The content of the JSON file: \n”, fileHandler2.read())

In the above example program, the dump() method uses three arguments. The dictionary object that is defined before will be considered in the first argument. The file handler variable that is also defined before creating a JSON file is considered in the second argument. And the indentation value s defined in the third argument. Finally, the output shows the content of the newly written JSON.

Therefore, this is how we convert a dictionary to JSON in the python programming language. These are ways you can follow for converting a python dictionary to JSON. I hope this article will be useful for you while you are learning and implementing the Python programming language.

Leave a Comment

Your email address will not be published.