-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32_json_tutorial.py
More file actions
192 lines (153 loc) · 4.53 KB
/
32_json_tutorial.py
File metadata and controls
192 lines (153 loc) · 4.53 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# Working with JSON in Python
import json
# ========== CONVERTING PYTHON → JSON ==========
# 1. dict → JSON string (serialization)
data = {
"name": "Pavel",
"age": 25,
"city": "Moscow",
"is_student": False,
"grades": [85, 90, 92]
}
json_string = json.dumps(data)
print(f"JSON string: {json_string}")
# 2. With formatting (pretty)
json_string = json.dumps(data, indent=4, ensure_ascii=False)
print(f"Formatted JSON:\n{json_string}")
# 3. Writing to file
with open('data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4, ensure_ascii=False)
# ========== CONVERTING JSON → PYTHON ==========
# 4. JSON string → dict (deserialization)
json_string = '{"name": "Pavel", "age": 25, "city": "Moscow"}'
data = json.loads(json_string)
print(f"Python object: {data}")
print(f"Name: {data['name']}")
# 5. Reading from file
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(f"From file: {data}")
# ========== JSON ⟷ PYTHON DATA TYPES ==========
# JSON → Python:
# object → dict
# array → list
# string → str
# number (int) → int
# number (real) → float
# true/false → True/False
# null → None
# 6. Example of all types
json_data = '''
{
"string": "text",
"number_int": 42,
"number_float": 3.14,
"boolean": true,
"null_value": null,
"array": [1, 2, 3],
"object": {"key": "value"}
}
'''
data = json.loads(json_data)
print(data)
# ========== WORKING WITH COMPLEX OBJECTS ==========
# 7. Nested structures
complex_data = {
"user": {
"name": "Pavel",
"contacts": {
"email": "pavel@example.com",
"phone": "+7 123 456 7890"
}
},
"posts": [
{"id": 1, "title": "First post"},
{"id": 2, "title": "Second post"}
]
}
# Accessing nested data
print(complex_data["user"]["contacts"]["email"])
print(complex_data["posts"][0]["title"])
# ========== ERROR HANDLING ==========
# 8. Handling invalid JSON
invalid_json = '{"name": "Pavel", "age": 25,}' # Extra comma
try:
data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print(f"JSON parsing error: {e}")
# ========== CUSTOM SERIALIZATION ==========
# 9. Serializing classes (doesn't work by default)
from datetime import datetime
class Person:
def __init__(self, name, age, birthday):
self.name = name
self.age = age
self.birthday = birthday
person = Person("Pavel", 25, datetime(2001, 1, 15))
# Error:
# json.dumps(person) # TypeError: Object of type Person is not JSON serializable
# 10. Custom encoder
class PersonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Person):
return {
"name": obj.name,
"age": obj.age,
"birthday": obj.birthday.isoformat()
}
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_string = json.dumps(person, cls=PersonEncoder, indent=4)
print(f"Custom serialization:\n{json_string}")
# 11. Alternative: function for serialization
def serialize_person(obj):
if isinstance(obj, Person):
return {
"name": obj.name,
"age": obj.age,
"birthday": obj.birthday.isoformat()
}
raise TypeError(f"Type {type(obj)} is not serializable")
json_string = json.dumps(person, default=serialize_person, indent=4)
print(json_string)
# ========== PRACTICAL EXAMPLES ==========
# 12. Loading configuration
config = {
"database": {
"host": "localhost",
"port": 5432,
"name": "mydb"
},
"debug": True
}
with open('config.json', 'w') as file:
json.dump(config, file, indent=4)
with open('config.json', 'r') as file:
loaded_config = json.load(file)
print(f"Database host: {loaded_config['database']['host']}")
# 13. API response
api_response = '''
{
"status": "success",
"data": {
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
}
'''
response = json.loads(api_response)
for user in response["data"]["users"]:
print(f"ID: {user['id']}, Name: {user['name']}")
# ========== DUMPS/DUMP PARAMETERS ==========
# indent - indentation for formatting
# ensure_ascii - False for unicode support
# sort_keys - sort keys
# separators - separators (compact: (',', ':'))
data = {"b": 2, "a": 1, "c": 3}
compact = json.dumps(data, separators=(',', ':'))
print(f"Compact: {compact}")
sorted_json = json.dumps(data, sort_keys=True, indent=2)
print(f"Sorted:\n{sorted_json}")