How To Read A Json File In Python

We will read a JSON file in Python, convert the data as a Python dictionary, loop through the said file and display both the keys and values using Python dictionary .items() method. With Python JSON package manipulating JSON is easy. We will use the load() method to load the JSON file and get the content. There is also the loads() method for loading JSON string. Here is an example of reading a JSON file with python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import json
# Opening JSON file
data_file = open("data.json", "r")

# json.loads returns a JSON file 
# as a Python Dictionary
data = json.load(data_file)

# Iterate through the json
# Get the Key and Values Python dictionary 
# .items()
for key,value in data.items():
    if isinstance(data.get(key), dict):
      print(f"\***Dictionary***/ {key} -> {value}")
    else:
      print(f"{key} ->{value}")

# It is very important to always close a file after usage 
# Close the open data file
data_file.close()

Related Posts

0 Comments

12345

    00