[practice]String & File Ops
JSON Handling
# theory
what JSON is
JSON (JavaScript Object Notation) is the standard format for data exchange. It looks like Python dictionaries and lists:
{
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding"],
"address": {
"city": "NYC",
"zip": "10001"
}
}
the json module
import json
# Parse JSON string → Python dict
data = json.loads('{"name": "Alice", "age": 30}')
print(data["name"]) # "Alice"
# Convert Python → JSON string
json_str = json.dumps({"name": "Bob", "age": 25})
print(json_str) # '{"name": "Bob", "age": 25}'
# Pretty print
json.dumps(data, indent=2)
json files
# Read JSON file
with open("data.json") as f:
data = json.load(f) # Note: load, not loads
# Write JSON file
with open("output.json", "w") as f:
json.dump(data, f, indent=2) # Note: dump, not dumps
nested access
data = {
"users": [
{"name": "Alice", "scores": [95, 82, 91]},
{"name": "Bob", "scores": [88, 79, 94]}
]
}
# Access nested data
first_user = data["users"][0]["name"] # "Alice"
first_score = data["users"][0]["scores"][0] # 95
json to DataFrame
import pandas as pd
# List of dicts → DataFrame
json_list = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
df = pd.DataFrame(json_list)
# Nested JSON → normalize
pd.json_normalize(data, record_path="users")# examples [3]
# example 01 · parsing and navigating JSON
Work with nested JSON structures
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
🐍
# example 02 · creating JSON
Convert Python objects to JSON strings
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🐍
# example 03 · JSON to DataFrame
Convert JSON arrays to pandas DataFrames
1
2
3
4
5
6
7
8
9
10
11
12
13
🐍
# challenges [2]
# challenge 01/02todo
Parse '{"items": [{"name": "A"}, {"name": "B"}]}' and print each item name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
🐍
# challenge 02/02todo
Convert students DataFrame to a JSON string and print it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
🐍
# project
# project-challenge
thread: Sales Performance Dashboard · reward: 50 xp
# brief
The API team needs the top 5 sales (by revenue) in JSON format for the mobile app. Convert the filtered sales data to a JSON string with proper formatting.
# task
Export Top Sales to JSON
# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
🐍