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 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
|
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
|
The below table will show you how the python objects will be converted into a JSON object.
Python |
JSON |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: [ |
To read the above file in python we need to write the below code
|
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 |
Output:
JSON string = {'name': 'Programming', 'languages': ['Python', 'Flutter', 'Java']} Python |
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 category = result['results'][0] |
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 :
|
|
|
|
1575 Views |