How to read JSON file using Python?

How to read JSON file using Python? The JSON design was initially enlivened by the sentence structure of JavaScript (a programming language utilized for web advancement). However, from that point forward it has turned into a language-free information organization and the majority of the programming dialects that we use today can produce and peruse JSON.

Since its initiation, JSON has rapidly turned into the accepted norm for data trade. Odds are you’re here on the grounds that you really want to move a few information from here to there. Maybe you’re gathering data through an API or putting away your information in an archive data set. Somehow, you’re overwhelmed with JSON, and you must Python out.

Fortunately, this is a typical errand, and—likewise with most normal assignments—Python makes it disgustingly simple. Have no dread, individual Pythoneers and Pythonistas. This present one will be a breeze!

A Brief History of JSON

Not really shockingly, JavaScript Object Notation was enlivened by a subset of the JavaScript programming language managing object exacting punctuation. They have a clever site that clarifies the entire thing. However, relax: JSON has since a long time ago become language rationalist and exists as its own norm, so we can, fortunately, keep away from JavaScript for this conversation.

Eventually, the local area in general embraced JSON on the grounds that it’s simple for the two people and machines to make and comprehend.

python read json

JSON file

Create a file on your disk (name it: example.json). The python program below reads the json file and uses the values directly.

The file can contain a one liner. The file content of example.json is:

{"usd":1,"eur":1.2,"gbp": 1.2}

Save the file to example.json.

python Example

Then create the program below and run it.:

import json

# read file
with open('example.json', 'r') as myfile:
    data=myfile.read()

# parse file
obj = json.loads(data)

# show values
print("usd: " + str(obj['usd']))
print("eur: " + str(obj['eur']))
print("gbp: " + str(obj['gbp']))

The above program will open the file ‘example.json’ and parse it. You can access the JSON data like any variable.

The full-type of JSON is JavaScript Object Notation. It implies that a content (executable) record which is made of text in a programming language, is utilized to store and move the information. Python upholds JSON through an inherent bundle called JSON. To utilize this component, we import the JSON bundle in Python script. The text in JSON is done through the cited string which contains the worth in key-esteem planning inside { }.

Perusing From JSON

It’s really simple to stack a JSON object in Python. Python has an inherent bundle called JSON, which can be utilized to work with JSON information. It’s finished by utilizing the JSON module, which gives us a ton of strategies which among burdens() and burden() techniques will assist us with perusing the JSON record.

Deserialization of JSON

The Deserialization of JSON implies the transformation of JSON objects into their separate Python objects. The heap()/loads() technique is utilized for it. In the event that you have utilized JSON information from one more program or gotten as a string configuration of JSON, then, at that point, it can without much of a stretch be deserialized with load()/loads(), which is normally used to stack from string, in any case, the root object is in list or dict. See the accompanying table given underneath.

JSON OBJECT PYTHON OBJECT
object dict
array list
string str
null None
number (int) int
number (real) float
true True
false False

json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

Syntax:

json.load(file object)

Example: Suppose the JSON file looks like this:

python-json

We want to read the content of this file. Below is the implementation.

# Python program to read
# json file
import json
# Opening JSON file
f = open('data.json')
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
    print(i)
# Closing file
f.close()

Output:

python-read-json-output

json.loads(): If you have a JSON string, you can parse it by using the json.loads() method.json.loads() does not take the file path, but the file contents as a string, using fileobject.read() with json.loads() we can return the content of the file.

Syntax:

json.loads(jsonstring) #for Json string

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

Example: This example shows reading from both string and JSON file. The file shown above is used.

# Python program to read
# json file
import json
# JSON string
a = '{"name": "Bob", "languages": "English"}'
# deserializes into dict
# and returns dict.
y = json.loads(a)
print("JSON string = ", y)
print()
# JSON file
f = open ('data.json', "r")
# Reading from file
data = json.loads(f.read())
# Iterating through the json
# list
for i in data['emp_details']:
    print(i)
# Closing file
f.close()

Output:

python-read-json-output

Also Read: How to Install PIP on Windows ?

Leave a Reply

Your email address will not be published. Required fields are marked *