JSON object trong Python được biểu diễn bằng dict. Truyền chuỗi JSON, parse bằng json.loads() bên trong hàm.
Ví dụ
import json
json_string = '{"name": "Rupert", "age": 25, "desig": "developer"}'
print(type(json_string)) #
def func(strng):
data = json.loads(strng) # Parse JSON string -> dict
print(type(data)) #
for k, v in data.items():
print(k, v)
print(dict(data))
func(json_string)
Đầu ra
desig developer age 25 name Rupert {'desig': 'developer', 'age': 25, 'name': 'Rupert'}
Cách tốt hơn: Truyền dict trực tiếp
def func(data: dict):
for k, v in data.items():
print(k, v)
data = {"name": "Rupert", "age": 25, "desig": "developer"}
func(data) # Không cần parse JSON
Chỉ dùng JSON string khi: Nhận từ network, file, CLI... Còn nội bộ Python thì truyền dict trực tiếp.