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

Python - วิธีแปลงสตริงเป็น JSON Object

ข้อมูลที่ส่งและรับใน API หลายตัวมักเป็นสตริงรูปแบบ JSON ต้องแปลงเป็นดิกชันนารีเพื่อนำไปประมวลผลต่อ

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

ใช้ json.loads() แปลงสตริง JSON เป็น Dictionary


import json

# เริ่มต้นดิกชันนารี (Python object)
ini_dict = {'vishesh': 1, 'ram': 5, 'prashant': 10, 'vishal': 15}

# แปลงเป็น JSON string ก่อน (เพื่อจำลองข้อมูลจาก API)
ini_string = json.dumps(ini_dict)
print("initial JSON string:", ini_string)
print("type:", type(ini_string))

# แปลงสตริง JSON กลับเป็น Dictionary
final_dictionary = json.loads(ini_string)

print("final dictionary:", str(final_dictionary))
print("type:", type(final_dictionary))

ผลลัพธ์


initial JSON string: {"vishal": 15, "ram": 5, "vishesh": 1, "prashant": 10}
type: 
final dictionary: {'vishal': 15, 'ram': 5, 'vishesh': 1, 'prashant': 10}
type: 

ฟังก์ชันหลักของโมดูล json

ฟังก์ชันทิศทางคำอธิบาย
json.loads()String → Python ObjectParse JSON string (Load from String)
json.load()File → Python ObjectParse JSON file (Load from File)
json.dumps()Python Object → StringSerialize to JSON string (Dump to String)
json.dump()Python Object → FileWrite JSON to file (Dump to File)

ตัวอย่างเพิ่มเติม


import json

# อ่านจากไฟล์
with open('data.json', 'r') as f:
    data = json.load(f)

# เขียนไปไฟล์ (pretty print)
with open('output.json', 'w') as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

# จัดการ error
json_string = '{"name": "John", "age": 30}'
try:
    data = json.loads(json_string)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")

สรุป

  • ใช้ json.loads() แปลง JSON string → dict
  • ใช้ json.load() อ่าน JSON จากไฟล์
  • ใช้ json.dumps() แปลง dict → JSON string
  • ใช้ json.dump() เขียน JSON ลงไฟล์
  • จับ exception json.JSONDecodeError สำหรับ JSON ที่ไม่ถูกต้อง