Encoding nested python object in JSON

前端 未结 5 2025
说谎
说谎 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 02:49

    I could not add this as a comment and adding as answer. Fred's final sample was useful for me.I was told jsonpickle does this, but could not get the module to install and run properly. So used the code here. Minor tweak though, I had way too many variables to add by hand to some of the objects. So this little loop simplified things:

    def reprJSON(self):
        d = dict()
        for a, v in self.__dict__.items():
            if (hasattr(v, "reprJSON")):
                d[a] = v.reprJSON()
            else:
                d[a] = v
        return d
    

    It can be used in any object that has a subclass that is too busy to hand encode. Or can be made a helper for all classes. This also works for the full JSON presentation of member arrays that contain other classes (as long as they implement reprJSON() of course).

提交回复
热议问题