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

วิธีอ่านไฟล์ JSON ใน Python

JSON File คืออะไร

JSON (JavaScript Object Notation) ใช้สำหรับแลกเปลี่ยนข้อมูลในเว็บแอปพลิเคชัน นามสกุลไฟล์คือ .json

ตัวอย่าง JSON

{
  "fruit": "Apple",
  "size": "Large",
  "color": "Red"
}
{
  "name": "Karan",
  "languages": ["English", "French"]
}

การอ่าน JSON ใน Python

ใช้ module json ที่ built-in มีฟังก์ชันหลัก 2 ตัว:

  • json.load(): อ่านจาก file object
  • json.loads(): parse จาก JSON string

ขั้นตอนการอ่านไฟล์

  1. import json
  2. เปิดไฟล์ด้วย open() mode 'r'
  3. ใช้ json.load(file) ได้ Python object (dict/list)
  4. ใช้ข้อมูลได้เลย

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

import json

with open('persons.json') as f:
    data = json.load(f)

print(data)
# Output: {'name': 'Karan', 'languages': ['English', 'French']}

ข้อควรระวัง

  • ไฟล์ต้องมีนามสกุล .json
  • ไฟล์ JSON และ Python script ต้องอยู่โฟลเดอร์เดียวกัน (หรือระบุ full path)
  • JSON ต้อง valid format (double quotes, ไม่มี trailing commas)

การเข้าถึงข้อมูล

print(data['name'])        # Karan
print(data['languages'][0]) # English