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

วิธีคืนค่า JSON object จากฟังก์ชัน Python

ใช้ json.dumps() แปลง dictionary เป็น JSON string แล้วคืนค่า

ตัวอย่าง

import json

a = {'name': 'Sarah', 'age': 24, 'isEmployed': True}

def retjson():
    python2json = json.dumps(a)
    print(python2json)

retjson()

ผลลัพธ์

{"age": 24, "isEmployed": true, "name": "Sarah"}

ค่าจะเป็น JSON string ที่พร้อมส่งผ่าน network หรือ API