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
ขั้นตอนการอ่านไฟล์
- import json
- เปิดไฟล์ด้วย open() mode 'r'
- ใช้ json.load(file) ได้ Python object (dict/list)
- ใช้ข้อมูลได้เลย
ตัวอย่างโค้ด
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