JSON Read in Python

Read a JSON file into a Python dictionary using the json module.

BeginnerFile Handling ProgramsExample 6 of 20
json-read.py
Run in browser
1# Program to read JSON from a file
2
3import json
4
5filename = input("Enter JSON filename: ")
6
7try:
8 with open(filename, "r", encoding="utf-8") as f:
9 data = json.load(f)
10 print("Loaded JSON object:", data)
11except FileNotFoundError:
12 print("JSON file not found.")
13except json.JSONDecodeError:
14 print("Invalid JSON format.")

Output

Enter JSON filename: config.json
Loaded JSON object: {'debug': True, 'version': 1}

What's going on

json.load parses the file contents into native Python objects (dicts, lists, etc.).