×

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the receiving and transmitting of data are simple between a web application and a server.

JSON is a built-in package in Python. we can import the json package in Python script to use the feature. The value in key-value mapping inside { } is contained by the quoted string. It helps to do the text in JSON.

About JSON

JSON(JavaScript Object Notation) refers to the JavaScript Object Notation. It is a Data format(open standard file format) and it is also called data exchange format that is used for representing structured data and is used to transmit and store data. JSON protocols are well known to programmers which include C++, C, Python, Java, Perl, etc.

  • JSON stands for JavaScript Object Notation.
  • The format was defined by Douglas Crockford.
  • It was developed for human-readable data interchange.
  • It has been derived from the JavaScript scripting language.
  • It is language-independent.
  • The filename is saved as .json.
  • The Internet Media Type of JSON is application/json.
  • The Identifier of Uniform Type is public.json.

Usage of JSON:

  • It is used while writing JavaScript-based applications that need browser extensions and websites.
  • JSON format can be used for transmitting and serializing structured data on a network connection.
  • It is originally used to transfer data among web applications and a server.
  • It is highly used by APIs and web services for providing public data.
  • It can be used with standard programming languages.

Characteristics of JSON:

  • This is easy to write and read.
  • It is a lightweight text-based exchange format.
  • It is language-independent.

Import JSON Module

We have to import the json package to work with JSON.

import json

Reading From JSON

Loadin a JSON object in Python is very easy. The built-in package named json in Python and it is used to work with JSON Files. json Module provides various methods such as load() and loads() methods are used in reading the JSON file.

Deserializing JSON

The load() and loads() methods in json library are used for converting the JSON objects into their identical Python objects.

the load() and loads() are easily deserialized the json data or string format of JSON. Normally load() and loads() load from string, unless the source object is in dict or list.

For example:

JSON                                    Python

Object                                      dict

array                                         list

string                                        str

number (int)                            int

number (real)                         float

true                                          True

false                                         False

null                                           None

Built-in Methods to Read JSON File

Below are the built-in json method which is used to read the JSON file in Python.

json.load() method

json.load() reads the JSON object file and converts the JSON data, then the Python dictionary is populated with the data and returns the identical python objects.

Syntax:

json.load(file object)

Example:

Consider a file having name Jhon.json and it contains JSOn object.

{"name": "Jhon", 

"languages": ["English", "French"]

}
import json

with open('path_to_file/Jhon.json') as f:

  data = json.load(f)

print(data)

Output:

{'name': 'Jhon', 'languages': ['English', 'French']}

json.loads() method

In json.loads() method, a JSON string can be parsed. it takes the file contents as a string, no matter that what's the file path is. 

the fileobject.read() is used with json.loads() to return the file content. 

Syntax:

json.loads(jsonstring) #for Json string

json.loads(fileobject.read()) #for fileobject

Example:

import json  

person_data = '{ "person": { "name": "Jhon", "sex": "male", "age": 32}}'

# converting JSON format in dictionary

dict_obj = json.loads(person_data)

print(dict_obj)

# check type of dict_obj

print("Type of dict_obj", type(dict_obj))

# get object details

print("Person......", dict_obj.get('person'))

Output:

{'person': {'name': 'Jhon', 'sex': 'male', 'age': 32}}

Type of dict_obj <class 'dict'>

Person...... {'name': 'Jhon', 'sex': 'male', 'age': 32}

Converting Python to JSON objects:

We can also convert Python dictionary objects into JSON objects with json.dumps() method.

Two parameters are used in json.dumps:

  • Dictionary: dictionary name which has to convert into JSON object.
  • indent: unit numbers are defined for indentation.

Syntax:

json.dumps(dict, indent)

Example:

import json

# Data

dictionary ={

  "id": "06",

  "name": "JHON",

  "depatment": "IT"

}

# Serializing 

json_object = json.dumps(dictionary, indent = 4)

print(json_object)

Output:

{

    "depatment": "IT",

    "id": "06",

    "name": "JHON"

}

Conclusion

In this tutorial, we have discussed the Pythom JSON read File. we have also learned about the JSON framework and its characteristics with uses. Now we understood how to covert the JSON objects into Python dictionary objects and vice versa.


Related Topics

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Python Parallel Processing

By performing more jobs concurrently, your software may complete more tasks in a shorter amount of time. These aid in solving major issues. The following subjects will be covered in...

2 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Augmented reality in python

In this article, we shall learn about augmented reality in python. Augmented reality is a technology that captures the world around you and adds virtual content or objects on top of...

3 minutes read.

Get Bounding Box Co-ordinates 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....

6 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

How to Install Numpy in PyCharm

What is PyCharm? JetBrains created the hybrid platform known as PyCharm as a Python IDE. The Python IDE PyCharm is used by some major companies, including Twitter, Facebook, Amazon, and many...

4 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

3 minutes read.