×

How to Parse JSON in Python

JSON

The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the data objects; it contains the variables and arrays. The JSON is independent of any programming language, and the JSON has a file extension of .json. The JSON is mainly used for the transmission of the data between a web application and a server; it acts the same as the transmitter in a communication device; both are mainly used for the transmission of the data. DouglasCrockford developed the JSON in 2001. The JSON has been derived from the javascript.

The JSON mainly consists of the two built-in functions or built-in methods.

  • JSON.parse( )- It is mainly used to convert the JSON standard file strings into the objects of the JavaScript programming language.
  • JSON.stringify( )- It is primarily used to convert an object in JavaScript into a JSON string.

JSON Python

Python programming language supports the JSON. The JSON provides the module that helps convert theJSON data into the python objects, such as dictionaries and strings. The data in the dictionary is stored in the key-value pair, and the data in the JSON is generally stored in the form of strings. Before parsing the data into the python dictionary, it is stored in the form of the string variable.

JSON String into Python Object

The data in the JSON is mainly stored in the form of strings; it can be parsed into the python dictionary. This operation can be performed by importing the JSON module. The JSON module consists of the two built-in functions or built-in methods to import the data- load and loads. To import a string, we generally use the loads module, which is read as 'load-s', that is, loading the string, whereas the load module is used when the data is in the form of bytes. The Boolean values in the JSON are read as true and false, which are converted into the python equivalent Boolean value 'True' and 'False'.

Example:

 Let us consider an example of the name of the company and the total number of products produced by the company as the JSON data.

JSON data:

{
     “company”: ‘Tata’,
      “Production”: 2514522,
}

Code:

#importing the JSON module
importJSON
#JSON string
motors = ‘{“company”: “Tata”, “Production”: 2514522}’
#displaying the type of the company before converting it to a python dictionary
print(type(company))
#Python dictionary
company_dict =json.loads(company)
#displaying the type of the company after converting it into the python dictionary.
print(type(company_dict))
#displaying the company
print(company_dict[‘company’])

Output:

<class ‘str’>
<class ‘dict’>
Tata

Here, we can observe that first, we need to import the JSON module before performing any operation before parsing the data into the python dictionary; the data in the JSON is first stored in the form of the JSON string. Then we used the inbuilt function of the JSON module JSON.loads(); we will then parse it into the python dictionary or python list depending upon the input string; that is, if the input string contains only one data as input, then it will be parsed as the list, and if the data contains more than one input it will be parsed as a dictionary.

Convert JSON File into Python Object

This process is similar to parsing the JSON data stored in the strings. In this method, we first read the JSON files and then parse the JSON data into the python data. Here we require the open( ) function to read the data in the JSON file, and we use the load( ) built-in function. Here we use the .jsonto store the file.

File:

Students_marks.json

{
    “name” : “Rohit”
    “Marks” : 97
    “Subject” : Mathematics
}

Code:

# importing the JSON module
importJSON
#opening the file
with open(‘Students_marks.json) as f:
data = json.load(f)
#displaying the data type
print(type(data))
#displaying the name of the student
print(data[‘name’])

Output:

<class ‘dict’>
Rohit

Here, we can observe that first, we need to import the JSON module before performing any operation; then, with the help of the   open( ) function, we need to read the file before parsing the data into the python dictionary the data in the JSON is first stored in the form of the JSON string. Then we used the inbuilt function of the JSON module JSON.load(); it will then be parsed into the python dictionary or python list depending upon the input string; that is, if the input string contains only one data as input, then it will be parsed as the list, and if the data contains more than one input it will be parsed as a dictionary.


Related Topics

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

Standard Scalar in Python

Python is a vast and open-source language that contains many libraries, modules, and functions. These functions in python are reusable codes where we don’t need to type the whole code...

4 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

Python Set difference() Method

Python Set difference() Method The set.difference() method in Python returns the set difference of two sets(A-B). Syntax set.difference(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return This method returns the difference of the two specified...

2 minutes read.

GUI Calendar using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

How to Convert int to str in Python

How to Convert int to str in Python In the last article, we studied how we convert a variable with string datatype to integer datatype and discussed different data types available...

4 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

PyShark 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....

4 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.