Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโค้ด Python อ่านข้อมูล JSON จากไฟล์ แปลงเป็น DataFrame และบันทึกเป็น CSV

สมมติว่าคุณมีไฟล์ JSONชื่อ pandas_sample.json และต้องการอ่าน แปลงเป็น DataFrame แล้วบันทึกเป็น CSV

ข้อมูล JSON ตัวอย่าง (pandas_sample.json)

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

วิธีแก้ปัญหา

  1. อ่าน JSON จากไฟล์ด้วย pd.read_json('pandas_sample.json')
  2. แปลงเป็น DataFrame ด้วย pd.DataFrame(data)
  3. บันทึกเป็น CSV ด้วย df.to_csv('pandas_json.csv')

ตัวอย่างโค้ด

import pandas as pd

# อ่าน JSON จากไฟล์
data = pd.read_json('pandas_sample.json')

# แปลงเป็น DataFrame
df = pd.DataFrame(data)

# บันทึกเป็น CSV
df.to_csv('pandas_json.csv')

print("แปลง JSON -> DataFrame -> CSV เรียบร้อย")
print(df)

ผลลัพธ์ (CSV)

,employee
age,31
name,emp1
salary,50000

คำอธิบาย:

  • read_json() อ่านไฟล์ JSON เข้ามาเป็น dict หรือ DataFrame ขึ้นอยู่กับโครงสร้าง
  • JSON ที่เป็น nested object จะกลายเป็น DataFrame ที่มี column เดียว (employee) และ index เป็น key ย่อย (age, name, salary)
  • to_csv() บันทึกเป็นไฟล์ CSV พร้อม index โดย default
  • ใช้ index=False ถ้าไม่ต้องการบันทึก index