DEV Community

Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

3

Nested json to python object

Today i was creating a configuration file, in the past, i accessed configuration as a dictionary, but this time, i think about changing that. The follwing code creates dynamic attributes with the objects keys recursively.

But first, i'll show the json object:

{
  "key": "value",
  "list": [
    "a",
    "b",
    "c",
    1,
    {
      "key": 1
    }
  ],
  "object": {
    "key": {
      "key": 1
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

On the conversion we have 3 cases:

  • lists
  • dicts (new object)
  • bool, int, float and str
import json

class AppConfiguration(object):
    def __init__(self, data=None):
        if data is None:
            with open("cfg.json") as fh:
                data = json.loads(fh.read())
        else:
            data = dict(data)

        for key, val in data.items():
            setattr(self, key, self.compute_attr_value(val))

    def compute_attr_value(self, value):
        if type(value) is list:
            return [self.compute_attr_value(x) for x in value]
        elif type(value) is dict:
            return AppConfiguration(value)
        else:
            return value
Enter fullscreen mode Exit fullscreen mode

Now the key, value pairs are attributes - objects.

instance = AppConfiguration()
>>>instance.key
'value'

>>>instance.list[4].key
1

>>> instance.object.key.key
1
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (1)

Collapse
 
ouzkagan profile image
ouzkagan

how can i create json file like your example from scratch in python

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more