简体   繁体   English

python 2.7:TypeError:<__ main __。nested_object对象位于0x…>不能序列化JSON

[英]python 2.7 : TypeError: <__main__.nested_object object at 0x…> is not JSON serializable

I'm trying to run the json.dumps method on a nested class/object and it fails on TypeError: <__main__.nested_object object at 0x...> is not JSON serializable 我正在尝试在嵌套的类/对象上运行json.dumps方法,并且在TypeError上失败:<__ main __。nested_object object at 0x ...>不是JSON可序列化的

What should I change in my class so I could call json.dumps method with input parameters of an implementation of JSONEncoder? 我应该在类中进行哪些更改,以便可以使用JSONEncoder实现的输入参数调用json.dumps方法?

Here is a very simple code that simulate the problem: 这是一个模拟问题的非常简单的代码:

class leaf_object(object):
    def __init__(self, s):
        self.value = s

class nested_object(object):
    def __init__(self, a, b_list):
        self.a = a
        self.b_list = b_list

if __name__ == "__main__":
    obj = nested_object('a1', [leaf_object('a1.1'),leaf_object('a1.2')])
    import json
    print(json.dumps(obj))

You can use subclass JSONEncoder and implement your own custom serialization.so use this code : 您可以使用子类JSONEncoder并实现自己的自定义序列化。因此请使用以下代码:

from json import JSONEncoder

class leaf_object(object):
    def __init__(self, s):
        self.value = s

class nested_object(object):
    def __init__(self, a, b_list):
        self.a = a
        self.b_list = b_list

class MyEncoder(JSONEncoder):
    def default(self, o):
        return o.__dict__
if __name__ == "__main__":
    obj = nested_object('a1', [leaf_object('a1.1'),leaf_object('a1.2')])
    obj=MyEncoder().encode(obj)
    import json
    print(json.dumps(obj))

this is the result: 结果是:

"{\"a\": \"a1\", \"b_list\": [{\"value\": \"a1.1\"}, {\"value\": \"a1.2\"}]}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM