×

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

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

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

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

5 minutes read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

How to find square root in python

How to find Square Root of a number In Python Python makes a lot of tasks easier by using different functions, modules, and libraires. There is an inbuilt function in Python...

6 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.