×

Dictionary to JSON Python

  • In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.
  • We can use many built-in packages which arenamedJSON.
  • Before using the packages, we have to import the package in python.
  • Let us consider an example program:
# import thejson packing
import json      
# Data to write  
dictionary ={ 
  "id": "02", 
  "name": "vijay", 
  "department": "Cr"
} 
      
# Serializing json  
json_obj = json.dumps(dictionary, indent = 2) 
print(json_obj)

Output:

“id”: “02”,
“name”: “vijay”,
 “department”: “CR”

Consider a program to convert a nested dictionary to JSON python:

# import thejson packing
import json
# data to be written
dictionary = {
 "fruit":{"guava": "1","color": "green"},
"vegetable": {"tomato": "2","color": "red"},
}
# using the json
d = json.dumps(dictionary)
print(d)

Output:

"fruit":
{"guava": "1","color": "green"},
"vegetable":
 {"tomato": "2","color": "red"}
  • In the above program, a module is imported. And we consider two different variables, fruits, and vegetables, Which are considered dictionaries.
  • A variable d is used. In which the json.dumps( ) function is used to store the dictionary.

Dictionary to JSON File Python

  • Let us consider an example program to convert a dictionary to json file in python.
# importing json packing
import json
st = {"Name": "Kumari","Age": 16,"hobby":"reading"}
with open('student.json', 'w') as f:
json.dump(st, f)

Output:

“name”: “kumari”,
“age”: 16,
“hobby”: “reading”
  • In the above program, we used a JSON module and used a student dictionary to open the file.
  • The name of the file is student.json, and ‘w’ is used to write the file.
  • The student.json file is stored in the dictionary the json.dump( ) module is used.

Converting Dictionary to JSON File in Python

  • Let us consider an example program to convert dictionary to json file in python.
# import thejson packing
import json
class fruit(dict):
    def __str__(self):
        return json.dumps(self)
c = [[‘apple’,'banana']]
q= fruit(combo)
print(q)

Output:

 “apple”: “orange”
  • In the above code, the JSON module is used.
  • The method__str__(self)  is used in the representation of the string.
  • Here we also declared the c and q variables where q is assigned to the class.
  • The parameter c is used to obtain the output.

Dictionary to JSON Array Python

  • Let us consider an example program to convert a dictionary to a JSON array in python.
# import thejson packing
import json
dic = {'lion': 3, 'tiger': 1}
arr = [ {'key': i, 'value': dic[k]} for i in dic]
print(json.dumps(arr))

Output:

{ “key”: “ lion “, “value ”: 3},
{ “key”: “ tiger “, “value”: 1}
  • In the above code, the JSON module is used.
  • Here the dic is a variable with assigned key-value pair.
  • The arr variable is used to declare the array, which can be used to check what is key and what is value.
  • The file is stored in the dictionary, the json.dump( ) module is used.
  • The loop is useful for storing of the value.

Multiple Dictionaries to JSON Python

  • Let us consider an example program to convert multiple dictionary to json file in python.
# import the json packing
import json
dict = {"fruit":{"mango": "1","color": "yellow"},"vegetable": {"onion": "4","white": "red"},"chocolate":{"dairy milk":"2","color":"black"}}
report = json.dumps(dict)
print(report)

Output:

{"fruit":{"mango": "1","color”: "yellow"},"vegetable": {"onion": "4","white": "red"},"chocolate":{"dairy milk":"2","color":"black"}}
  • In the above code, the JSON module is used. And a variable dict is declared.
  • We used json.dumps ( ) module to store the data in the dictionary.

Dictionary to JSON Using the Sort_keys in Python

  • Let us consider an example program to convert a dictionary to json file using sort_keysin python.
# import thejson packing
import json
dictionary ={"Name": "rushi", "Branch": " ECE ", "CGPA": " 8.0"} 
d = json.dumps(dict, indent = 5, sort_keys = True) 
print(d)

Output:

" Branch ": " ECE ",
" CGPA ": " 8.0"
" Name ": " rushi ", 
  • In the above code, the JSON module is used.
  • Here the dic is a variable with assigned key-value pair.
  • We used json.dumps module to store the values.
  • The sort_keys is TRUE, which is used to sort the values in thedictionary. If the value is false then the values will not be sorted.

Related Topics

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Anytree Python

Python's anytree module is frequently used within data science-related software. Anytree has a Tolerant License, a Construct File that is public, no errors, no risks, and excellent support. One may...

3 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

How to reverse a string in Python

In Python language, we have a few ways to reverse a string. In this article, let us discuss these ways and understand the suitability of these ways in different scenarios...

5 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.