How to retrieve data from json in python
Step-by-Step Guide
Step 1: Import the json module
python
CopyEdit
import json
Step 2: Load JSON data (string or file)
Option A: From a JSON string
json_str = '{"name": "Alice", "age": 30, "city": "New York"}' data = json.loads(json_str) # Converts string to Python dict
Option B: From a JSON file
python
CopyEdit
with open('data.json') as file: data = json.load(file) # Reads and converts file to Python dict
Step 3: Access data like a dictionary
print(data["name"]) # Output: Alice print(data["age"]) # Output: 30
import json # Sample JSON string json_str = ''' { "student": { "name": "John", "grades": [90, 85, 88], "passed": true } } ''' # Load the JSON into a Python dict data = json.loads(json_str) # Access nested data print(data["student"]["name"]) # John print(data["student"]["grades"][1]) # 85 print(data["student"]["passed"]) # True
Tip:
-
JSON maps directly to Python types:
-
object→dict -
array→list -
string→str -
number→intorfloat -
true/false→True/False -
null→None
-