轉換 JSON 資料
當你把 JSON 格式的資料讀入字典時,通常需要先對資料做一些手動轉換,才能儲存到 DataFrame。處理巢狀字典時特別常見,這個練習會帶你實作看看。
"nested_school_scores.json" 檔案已讀入字典並存在變數 raw_testing_scores 中,結構如下:
{
"01M539": {
"street_address": "111 Columbia Street",
"city": "Manhattan",
"scores": {
"math": 657,
"reading": 601,
"writing": 601
}
}, ...
}
本練習屬於課程
使用 Python 的 ETL 與 ELT
練習說明
- 同時迭代
raw_testing_scores字典的鍵與值。 - 從
raw_testing_scores物件中每個巢狀字典擷取"street_address"。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
normalized_testing_scores = []
# Loop through each of the dictionary key-value pairs
for school_id, school_info in raw_testing_scores.____():
normalized_testing_scores.append([
school_id,
school_info.____("____"), # Pull the "street_address"
school_info.get("city"),
school_info.get("scores").get("math", 0),
school_info.get("scores").get("reading", 0),
school_info.get("scores").get("writing", 0),
])
print(normalized_testing_scores)