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

การจัดรูปแบบ JSON ใน Python

JSON (JavaScript Object Notation) คือรูปแบบแลกเปลี่ยนข้อมูลที่เบาและยอมรับทั่วไป ใน Python ใช้โมดูล json (standard library) แปลงระหว่าง JSON string และ Python objects

1. แปลง Python Objects → JSON String

เมธอดสำคัญ 2 ตัว:

  • json.dump(obj, file) - เขียน JSON ลงไฟล์ (stream)
  • json.dumps(obj) - แปลง object เป็น JSON string

ตัวอย่าง


import json
from io import StringIO

# json.dump เขียนลง file-like object
str_io_obj = StringIO()
json.dump(["India", "Australia", "Brazil"], str_io_obj)
print('StringIO Object value:', str_io_obj.getvalue())

# json.dumps แปลงเป็น string
my_json = {
    "name": "Kalyan",
    "age": 25,
    "city": "Delhi"
}
print(json.dumps(my_json, indent=4))

ผลลัพธ์


StringIO Object value: ["India", "Australia", "Brazil"]
{
    "name": "Kalyan",
    "age": 25,
    "city": "Delhi"
}

2. แปลง JSON String → Python Objects

  • json.load(file) - อ่านจาก file object
  • json.loads(string) - แปลงจาก string

ตัวอย่าง


import json
from io import StringIO

# load จาก StringIO
str_io_obj = StringIO('["xyz", "abc", "xyz", "pqr"]')
print('Load:', json.load(str_io_obj))

# loads จาก string
json_str = '{"xyz": 1, "abc": 2, "xyz": 3, "pqr": 4}'
print('String to Json:', json.loads(json_str))

ผลลัพธ์


Load: ['xyz', 'abc', 'xyz', 'pqr']
String to Json: {'xyz': 3, 'abc': 2, 'pqr': 4}

หมายเหตุ: JSON ไม่อนุญาต key ซ้ำ คีย์ 'xyz' ตัวหลังจะทับตัวก่อน

3. JSON Encoder และ Decoder แบบกำหนดเอง

Custom Encoder: แปลง Complex Number


import json

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return super().default(obj)

print(json.dumps(5+8j, cls=ComplexEncoder))
# [5.0, 8.0]

Custom Decoder


import json

my_str = '{"Asim": 25, "Priyesh": 23, "Asim": "28"}'
decoded = json.JSONDecoder().decode(my_str)
print(decoded)
# {'Asim': '28', 'Priyesh': 23}

# raw_decode คืนค่า (obj, end_index)
print(json.JSONDecoder().raw_decode(my_str))
# ({'Asim': '28', 'Priyesh': 23}, 44)

สรุปฟังก์ชันหลัก

ฟังก์ชันInputOutputใช้เมื่อไหร่
dumps()Python objectJSON stringต้องการ string เพื่อส่ง/เก็บ
dump()Python object + fileเขียนไฟล์บันทึกลงไฟล์
loads()JSON stringPython objectอ่านจาก string/response
load()file objectPython objectอ่านจากไฟล์