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

วิธีส่ง JSON object เป็นพารามิเตอร์ให้ฟังก์ชัน Python

ส่ง JSON string เข้าฟังก์ชัน แล้วใช้ json.loads() แปลงเป็น dictionary

ตัวอย่าง

import json

json_string = '{"name":"Rupert", "age": 25, "desig":"developer"}'
print(type(json_string))  # 

def func(strng):
    a = json.loads(strng)
    print(type(a))        # 
    for k, v in a.items():
        print(k, v)
    print(dict(a))

func(json_string)

ผลลัพธ์

<class 'str'>
<class 'dict'>
desig developer
age 25
name Rupert
{'desig': 'developer', 'age': 25, 'name': 'Rupert'}