Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đọc file JSON chuyển DataFrame và xuất CSV Python pandas

Giả sử bạn có file JSON pandas_sample.json và muốn đọc, chuyển thành DataFrame, sau đó xuất ra CSV.

Nội dung file JSON

{
  "employee": {
    "name": "emp1",
    "salary": 50000,
    "age": 31
  }
}

Giải pháp

  • Đọc JSON: pd.read_json('pandas_sample.json').
  • Chuyển thành DataFrame: pd.DataFrame(data).
  • Xuất CSV: df.to_csv('pandas_json.csv').

Mã ví dụ

import pandas as pd

data = pd.read_json('pandas_sample.json')
df = pd.DataFrame(data)
df.to_csv('pandas_json.csv', index=False)

print("Đã xuất CSV. Nội dung file:")
print(df.to_csv(index=False))

Kết quả

employee
age,31
name,emp1
salary,50000

Giải thích:

  • read_json với JSON object lồng nhau tạo DataFrame có cột là key ngoài ('employee'), hàng là key trong.
  • to_csv(index=False) không ghi index.
  • JSON phức tạp hơn (list of records) dùng orient='records'.