eclipse - python如何把json字符串转换成自定义的对象
PHP中文网
PHP中文网 2017-04-18 09:02:58
[Python讨论组]

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

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))
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号