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]}]
那加個 object_hook
看了下你的問題不需要object_hook..
直接簡單粗暴
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))
update: 修改一下格式 然後你response=[]
這種寫法是不推薦的
所以最後可用的結果:
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))