- json — JSON encoder and decoder — Python 3.10.4 documentation
- How to convert a JSON string to a dictionary in Python (adamsmith.haus)
- Python JSON to Dictionary – Python Examples
Example1
สร้างตัวแปรแบบ str
แล้วค่อยทำเป็น
ด้วย dict
json.loads()
import json json_string = """ { "id": "abc123", "name": "Bob" } """ json_object = json.loads(json_string) print(type(json_object)) # <class 'dict'> print(json_object["id"]) # abc123 data = json.dumps(json_object) print(type(data)) # <class 'str'> print(data) # {"id": "abc123", "name": "Bob"}
Example2
import json jsonString = '{"a":54, "b": {"c":87}}' aDict = json.loads(jsonString) print(aDict) print(aDict['a']) print(aDict['b']) print(aDict['b']['c'])
{'a': 54, 'b': {'c': 87}} 54 {'c': 87} 87
Example3
import json name = "Jack" json_string = """ { "id": "abc123", "name": "" } """ json_object = json.loads(json_string) # <class 'str'> json_object["name"] = name print(type(json_object)) # <class 'dict'> print(json_object) # {'id': 'abc123', 'name': 'Jack'} data = json.dumps(json_object) print(type(data)) # <class 'str'> print(data) # {"id": "abc123", "name": "Jack"}
Example4
สร้างตัวแปรแบบ dict
แล้วค่อยทำเป็น str
ด้วย json.dumps()
import json json_dict = {} json_dict['id'] = '456' json_dict['name'] = 'Jack' print(type(json_dict)) # <class 'dict'> print(json_dict) # {'id': 'abc123', 'name': 'Jack'} data = json.dumps(json_dict) print(type(data)) # <class 'str'> print(data) # {"id": "abc123", "name": "Jack"}