從python2.6開始,python標準庫中添加了對json的支援,操作json時,只需要import json即可,藉助的api,簡單來說就是兩個
物件轉json ----------- json.dumps()
json轉物件 ----------- json.loads()
class Student(object):
def __init__(self, name, age, score,reward):
self.name = name
self.age = age
self.score = score
self.reward = reward
def dict2student(d):
return Student(d["name"], d["age"], d["score"],d["reward"])
json_str = "{"name": "Bob", "age": 20, "score": 88, "reward": ["三好學生", "優秀團幹", "最佳辯手"]}"
student = json.loads(json_str,object_hook=dict2student)
print(type(student))
從python2.6開始,python標準庫中添加了對json的支援,操作json時,只需要import json即可,藉助的api,簡單來說就是兩個
物件轉json ----------- json.dumps()
json轉物件 ----------- json.loads()
class Student(object):
def __init__(self, name, age, score,reward):
self.name = name
self.age = age
self.score = score
self.reward = reward
def dict2student(d):
return Student(d["name"], d["age"], d["score"],d["reward"])
json_str = "{"name": "Bob", "age": 20, "score": 88, "reward": ["三好學生", "優秀團幹", "最佳辯手"]}"
student = json.loads(json_str,object_hook=dict2student)
print(type(student))