攝影或3C

Python Pandas:to_json( orient = “records” ) 與 to_dict( orient = “records” ) 圖文教學與常見陷阱

加入好友加入好友
加入社群加入社群
Python Pandas:to_json( orient = "records" ) 與 to_dict( orient = "records" ) 圖文教學與常見陷阱 - 儲蓄保險王Python Pandas:to_json( orient = "records" ) 與 to_dict( orient = "records" ) 圖文教學與常見陷阱 - 儲蓄保險王

Pandas 是 Python 最常用的資料分析套件,to_json()to_dict() 則是 DataFrame 轉換成 Python 原生物件或 JSON 格式的超實用工具。不論你要跟前端溝通、存檔、或是傳給 API,都會用到。這篇用簡單範例帶你一次搞懂這兩個方法的用法、參數、和常見錯誤!


一、準備一個簡單的 DataFrame

import pandas as pd

df = pd.DataFrame({
    'name': ['Amy', 'Brian'],
    'score': [90, 85]
})
print(df)

輸出結果:

Python Pandas:to_json( orient = "records" ) 與 to_dict( orient = "records" ) 圖文教學與常見陷阱 - 儲蓄保險王Python Pandas:to_json( orient = "records" ) 與 to_dict( orient = "records" ) 圖文教學與常見陷阱 - 儲蓄保險王

二、to_dict() 的用法與 orient 參數

預設用法(orient="dict"

d = df.to_dict()
print(d)

輸出結果:

不論有沒有寫
orient="dict"
輸出結果都一樣

常見 orient 參數:

orient:

最常用的是 "records"

records = df.to_dict(orient="records")
#List[dict]
print(records)
# [{'name': 'Amy', 'score': 90}, {'name': 'Brian', 'score': 85}]

三、to_json() 的用法與 orient 參數

預設用法(orient="columns"

j = df.to_json()
print(j)

輸出結果:

(這不是最直覺的格式)

最常用 orient="records"

j = df.to_json(orient="records", force_ascii=False)
print(j)

輸出結果:

這種格式最適合前端、API、NoSQL 交換。


四、常見錯誤與解法

1. 縮排問題:

  • df.to_json() 產生的 JSON 字串沒縮排
  • 如果你想要縮排、好閱讀的 JSON,應該先轉成 to_dict(),再用 json.dump() 輸出:
import json

data = df.to_dict(orient="records")
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

2. MultiIndex 錯誤:

  • 如果你的 DataFrame 欄位名稱是 tuple(多層欄位),to_dict() 轉 JSON 會報錯。
  • 解法:請平坦化欄位名稱
#1. 只保留 tuple 的第一層欄位名
df.columns = [col[0] if isinstance(col, tuple) else col for col in df.columns]

#2.  join 合併所有欄位層級
df.columns = ['_'.join(map(str, col)) if isinstance(col, tuple) else col for col in df.columns]

用 join 合併所有欄位層級:

五、總結與選擇建議

  • 交換資料給前端/API → 用 to_json(orient="records")to_dict(orient="records")
  • 要寫成美觀的 JSON 檔案 → 先 to_dict(orient="records"),再用 json.dump(..., indent=4)
  • 表格欄位有多層 → 記得先平坦化欄位名稱

六、常用小抄

# DataFrame  Python 物件 (list of dict)
data = df.to_dict(orient="records")

# DataFrame 直接轉 JSON 字串
json_str = df.to_json(orient="records", force_ascii=False)

# 美觀輸出 JSON 檔案
import json
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=4)

七、延伸閱讀

推薦hahow線上學習python: https://igrape.net/30afN

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡