Rumah > Soal Jawab > teks badan
python如何把json字符串转换成自定义的对象
class Result(object):
def __init__(self, code,message, response=[]):
self.code=code
self.message = message
self.response = response
这是json字符串:str: {"code":200,"message":"发送成功","response":[{"code":2,"message":"xxxxxxxx","mobile":"xxxxxx","taskId":null},{"code":2,"message":"xxxxxx","mobile":"xxxxxx","taskId":null}]}
PHP中文网2017-04-18 09:04:58
json.loads()
https://docs.python.org/2.7/library/json.html
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
Tambahkan cangkuk_objek
Selepas membaca soalan anda, object_hook tidak diperlukan..
Mudah dan kasar
test_str = '{"code":200,"message":"发送成功","response":[{"code":2,"message":"xxxxxxxx","mobile":"xxxxxx","taskId":null},{"code":2,"message":"xxxxxx","mobile":"xxxxxx","taskId":null}]}'
result = Result(**json.loads(test_str))
kemas kini: Ubah suai format dan kemudian anda response=[]
Cara penulisan ini tidak disyorkan
Jadi hasil terakhir yang tersedia:
import json
class Result(object):
def __init__(self, code, message, response=None):
if response is None:
response = []
self.code = code
self.message = message
self.response = response
test_str = '{"code":200,"message":"发送成功","response":[{"code":2,"message":"xxxxxxxx","mobile":"xxxxxx","taskId":null},{"code":2,"message":"xxxxxx","mobile":"xxxxxx","taskId":null}]}'
result = Result(**json.loads(test_str))