2024-06-08|閱讀時間 ‧ 約 26 分鐘

[Python]解讀JSON

解讀JSON 字串

首先,你需要使用 Python 的 json 模組來解讀JSON 字串。

JSON的基本結構:

由花括號 {} 包圍,內部是鍵值對的集合,每個鍵值對之間用逗號分隔。

鍵是字串類型,值可以是任何JSON支持的資料類型(字串、數字、布林值、陣列、物件或 null)。

{
"name": "Alice", // 字符串
"age": 25, // 數字
"isStudent": false, // 布林值
"address": { // 巢式物件
"city": "New York",
"zipcode": "10001"
},
"hobbies": [ // 陣列
"reading",
"traveling",
"swimming"
],
"middleName": null, // null 值
"grades": [ // 陣列,包含數字
88,
92,
79
],
"profile": { // 巢式物件,包含布林值和字符串
"active": true,
"email": "alice@example.com"
},
"preferences": [ // 陣列,包含巢式物件
{
"theme": "dark",
"notifications": true
},
{
"theme": "light",
"notifications": false
}
]
}

以下是如何讀取JSON 字串的範例:

import json

# JSON 字串
json_str = '{"name": "Alice", "age": 25, "city": "New York"}'

# 讀取JSON 字串
data = json.loads(json_str)

# 顯示JSON的資料
print(data)
print(type(data)) # 確認資料類型為 dict

查詢 JSON 資料

一旦你讀取了 JSON 字串並將其轉換為 Python 字典,你就可以像查詢普通字典一樣查詢資料。例如:

# 查詢資料
name = data['name']
age = data['age']
city = data['city']

print(f"Name: {name}") # Name: Alice
print(f"Age: {age}") # Age: 25
print(f"City: {city}") # City: New York

更複雜的 JSON 結構

如果你的 JSON 結構更加複雜,例如包含巢式的結構,你可以使用類似的方法進行查詢。例如:

import json
# 複雜的 JSON 字串

json_str = '''
{
"name": "Alice",
"age": 25,
"address": { // 巢式物件
"city": "New York",
"zipcode": "10001"
},
"hobbies": ["reading", "traveling", "swimming"]
}
'''

# 解析 JSON 字串
data = json.loads(json_str)

# 查詢巢式物件內資料
city = data['address']['city']
zipcode = data['address']['zipcode']
hobbies = data['hobbies']

print(f"City: {city}") # City: New York
print(f"Zipcode: {zipcode}") # Zipcode: 10001
print(f"Hobbies: {', '.join(hobbies)}") # Hobbies: reading, traveling, swimming





分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.