Encoding nested python object in JSON

前端 未结 5 2018
说谎
说谎 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:00

    my previous sample, with another nested object and your advices :

    import json
    
    class Identity:
        def __init__(self):
            self.name="abc name"
            self.first="abc first"
            self.addr=Addr()
        def reprJSON(self):
            return dict(name=self.name, firstname=self.first, address=self.addr) 
    
    class Addr:
        def __init__(self):
            self.street="sesame street"
            self.zip="13000"
        def reprJSON(self):
            return dict(street=self.street, zip=self.zip) 
    
    class Doc:
        def __init__(self):
            self.identity=Identity()
            self.data="all data"
        def reprJSON(self):
            return dict(id=self.identity, data=self.data) 
    
    class ComplexEncoder(json.JSONEncoder):
        def default(self, obj):
            if hasattr(obj,'reprJSON'):
                return obj.reprJSON()
            else:
                return json.JSONEncoder.default(self, obj)
    
    doc=Doc()
    print "Str representation"
    print doc.reprJSON()
    print "Full JSON"
    print json.dumps(doc.reprJSON(), cls=ComplexEncoder)
    print "Partial JSON"
    print json.dumps(doc.identity.addr.reprJSON(), cls=ComplexEncoder)
    

    produces the expected result :

    Str representation
    {'data': 'all data', 'id': <__main__.Identity instance at 0x1005317e8>}
    Full JSON
    {"data": "all data", "id": {"name": "abc name", "firstname": "abc first", "address": {"street": "sesame street", "zip": "13000"}}}
    Partial JSON
    {"street": "sesame street", "zip": "13000"}
    

    Thanks.

提交回复
热议问题