
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to read JSON file in Python
What is a JSON file?
JSON stands for JavaScript Object Notation. It is commonly used for transmitting data in web applications( such as sending data from server to client to display on the web pages).
Sample JSON File
Example 1: { "fruit": "Apple", "size": "Large", "color": "Red" }
Example 2: { 'name': 'Karan', 'languages': ['English', 'French'] }
The json file will have .json extension
Read JSON file in Python
Python has an in-built package called json which can be used to work with JSON data and to read JSON files. The json module has many functions among which load() and loads() are used to read the json files.
load() − This function is used to parse or read a json file.
loads() − This function is used to parse a json string.
To use json module in python, we need to import it first. The json module is imported as follows −
import json
Suppose we have json file named “persons.json” with contents as shown in Example 2 above. We want to open and read it using python. This can be done in following steps −
Import json module
Open the file using the name of the json file witn open() function
Open the file using the name of the json file witn open() function
Read the json file using load() and put the json data into a variable.
Use the data retrieved from the file or simply print it as in this case for simplicty.
Example
import json with open('persons.json') as f: data = json.load(f) print(data)
Output
{'name': 'Karan', 'languages': ['English', 'French']}
Note:
Make sure the json file is saved with .json extension on your system.
Make sure the json file and the python program are saved in the same directory on your system, else an exception would be raised.
- Related Articles
- How to read an external JSON file in JavaScript
- How to read a JSON file into a DataFrame using Python Pandas library?
- How can we read a JSON file in Java?
- How to read CSV file in Python?
- How to read the contents of a JSON file using Java?
- How to read a text file in Python?
- How to open a file just to read in python?
- How to put a Pandas DataFrame into a JSON file and read it again?
- How to read a text file in Selenium with python?
- How to read volley json array in android?
- Write a Python code to read JSON data from a file and convert it to dataframe, CSV files
- How do I read a .data file in Python?
- How to set read and write position in a file in Python?
- How to read a file from command line using Python?
- How to open a file in read and write mode with Python?
