在我們實際的業務開發中,有時需要抽象一個對象(類的實例化),然後需要將對象轉為json字符串作為輸出進行加工處理
如下代碼是示例,僅供參考
import json
class Test:
""" age name """
# init args :age、sname
age = 0
name = ''
def obj_json():
""" convert object to json str :return json str: """
test = Test()
test.age = 20
test.name = 'kitty'
list_test = []
list_test.append(test)
test = Test()
test.age = 30
test.name = 'hello'
list_test.append(test)
json_str = json.dumps(list_test, default=lambda o: o.__dict__)
print(json_str)
return json_str
res = obj_json()
print('object convert json:' + res)