Home  >  Q&A  >  body text

eclipse - python如何把json字符串转换成自定义的对象

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中文网2741 days ago313

reply all(1)I'll reply

  • PHP中文网

    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]}]

    Then add an object_hook

    After reading your question, you don’t need object_hook..

    Simple and crude

    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: Modify the format and your response=[]writing method is not recommended

    So the final available results:

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

    reply
    0
  • Cancelreply