Read JSON file in Python | Python JSON

Published December 23, 2020

In this post, we will learn how to read JSON files in python with different examples.

We all know the data between server and web application is in the form of JSON, to show this JSON data on the UI we need to parse this JSON data. 

This post will cover 

  • Read JSON file
  • Parse JSON object local
  • Parse Json data from the network

 

Read Top 10 features of python you should know

 

What is JSON?

JSON stands for JavaScript Object Notation, is a widely used data format to display structured data. 

 

Every JSON data is in the form of String and could be like this

data = '{"name": "Programming", "languages": ["Python", "Flutter","Java"]}'

 

In python to work with json we need to import json module in the python file. This json module is a built-in package in python.

Let's import like

import json

 

The below table will show you how the python objects will be converted into a JSON object.

Python

JSON

dict

object

listtuple

array

str

string

intlongfloat

number

True

true

False

false

None

null

 

 

This module provides different methods to read json file .

json module contains load() and loads() method.

These two methods will perform different operation like

 

json.loads(): json.load() will take the file objects and parse the json data 

json.load(file obj)

 

For example, if the given JSON file looks like

results: [
        {
        "category": "Entertainment: Video Games",
        "type": "multiple",
        "difficulty": "easy",
        "question": "Which of these levels does NOT appear in the console/PC versions of the game "Sonic Generations"?",
        "correct_answer": "Mushroom Hill",
        "incorrect_answers": [
                "City Escape",
                "Planet Wisp",
                "Sky Sanctuary"
                ]
        },
{
        "category": "Entertainment: Video Games",
        "type": "multiple",
        "difficulty": "easy",
        "question": "Which of these levels does NOT appear in the console/PC versions of the game "Sonic Generations"?",
        "correct_answer": "Mushroom Hill",
        "incorrect_answers": [
                "City Escape",
                "Planet Wisp",
                "Sky Sanctuary"
                ]
        },
]

 

 

To read the above file in python we need to write the below code

 

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()

 

it will return json data as a string from the given file.

 

json.loads(): json.loads() will be used when we have a json string, that we need to parse this json string then we will pase this json string to json.loads() method.

 

json.loads(jsonstring) #for Json string

json.loads(fleObj.read()) #for given file object

 

Example to parse python json data

import json 
  
  
# JSON string 
data = '{"name": "Programming", "languages": ["Python", "Flutter","Java"]}'
  
# deserializes into dict  
# and returns dict. 
jsondata = json.loads(data) 
  
print("JSON string = ", jsondata) 
print() 
  
  
for i in jsondata['languages']: 
    print(i) 

 

Output: 

JSON string =  {'name': 'Programming', 'languages': ['Python', 'Flutter', 'Java']}

Python
Flutter
Java

 

 

Read json from Netwrork and parse json data

The below example will show how to read json file from the server and parse it. 

In this example i have used a REST API from OpenDB database

import requests
r = requests.get('https://opentdb.com/api.php?amount=10')
result = r.json()

category = result['results'][0]
print(category)

 

This will return below output

{

'category': 'Geography',

'type': 'multiple',

'difficulty': 'easy',

'question': 'Which of these is NOT an Australian state or territory?',

'correct_answer': 'Alberta',

'incorrect_answers':

['New South Wales',

'Victoria', 'Queensland'

]

}

 

Conclusion: Now we are successfully learned how to parse json file in python with json module, and also learned how to fetch data from the server and parse it in python file.

 

 

Tags: Python json, Parse json in python, Python read json file

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1448 Views