Encoding nested python object in JSON

前端 未结 5 2020
说谎
说谎 2020-12-08 02:37

I want to encode objects in JSON. But, I can not figure out how to make the output without the string escaping.

import json

class Abc:
    def __init__(self         


        
5条回答
  •  既然无缘
    2020-12-08 03:05

    So, the immediate problem is that you're passing the json module a JSON value, which will get encoded as just another string in the JSON value.

    The broader problem is that you're greatly overcomplicating this.

    Drawing on JSON datetime between Python and JavaScript, I'd go with something closer to this:

    import json
    
    class Abc:
        def __init__(self):
            self.name="abc name"
        def jsonable(self):
            return self.name
    
    class Doc:
        def __init__(self):
            self.abc=Abc()
        def jsonable(self):
            return self.__dict__
    
    def ComplexHandler(Obj):
        if hasattr(Obj, 'jsonable'):
            return Obj.jsonable()
        else:
            raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(Obj), repr(Obj))
    
    doc=Doc()
    print json.dumps(doc, default=ComplexHandler)
    

    which gets you:

    ~$ python nestjson.py 
    {"abc": "abc name"}
    ~$ 
    

    This can be made cleaner/saner/safer (in particular, just grabbing __dict__ isn't generally a recommended thing to do outside debugging/troubleshooting), but it should get the point across. All you need, fundamentally, is a way to get a json-compatible object (whether that's a simple string or number, or a list or dict) out of each "node" in the tree. That object should not be an already-JSON-serialized object, which is what you were doing.

提交回复
热议问题