eclipse - python如何把json字符串转换成自定义的对象
PHP中文网
PHP中文网 2017-04-18 09:02:58
0
1
299

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中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
Ty80

json.loads()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=[]

https://docs.python.org/2.7/library/json.html

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))

那加个 object_hook🎜 🎜看了下你的问题不需要object_hook..🎜 🎜直接简单粗暴🎜 rrreee
🎜update: 修改一下格式 然后你response=[]这种写法是不推荐的🎜 🎜所以最后可用的结果:🎜 rrreee
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!