Recursive function to create hierarchical JSON object?

后端 未结 5 1974
庸人自扰
庸人自扰 2021-02-08 19:08

I\'m just not a good enough computer scientist to figure this out by myself :(

I have an API that returns JSON responses that look like this:

// call to         


        
5条回答
  •  醉话见心
    2021-02-08 19:46

    I had the same problem this afternoon, and ended up rejigging some code I found online.

    I've uploaded the code to Github (https://github.com/abmohan/objectjson) as well as PyPi (https://pypi.python.org/pypi/objectjson/0.1) under the package name 'objectjson'. Here it is below, as well:

    Code (objectjson.py)

    import json
    
    class ObjectJSON:
    
      def __init__(self, json_data):
    
        self.json_data = ""
    
        if isinstance(json_data, str):
          json_data = json.loads(json_data)
          self.json_data = json_data
    
        elif isinstance(json_data, dict):
          self.json_data = json_data
    
      def __getattr__(self, key):
        if key in self.json_data:
          if isinstance(self.json_data[key], (list, dict)):
            return ObjectJSON(self.json_data[key])
          else:
            return self.json_data[key]
        else:
          raise Exception('There is no json_data[\'{key}\'].'.format(key=key))
    
      def __repr__(self):
        out = self.__dict__
        return '%r' % (out['json_data'])
    

    Sample Usage

    from objectjson import ObjectJSON
    
    json_str = '{ "test": {"a":1,"b": {"c":3} } }'
    
    json_obj = ObjectJSON(json_str)
    
    print(json_obj)           # {'test': {'b': {'c': 3}, 'a': 1}}
    print(json_obj.test)      # {'b': {'c': 3}, 'a': 1}
    print(json_obj.test.a)    # 1
    print(json_obj.test.b.c)  # 3
    

提交回复
热议问题