skip to Main Content

What I’m trying to do is to create Python class definitions in code by reading a JSON file.

I don’t want to have the class pre-written in Python and then load it with the JSON data. I want to use the JSON file to create the Python code for the class definition. I realize it’s not possible to assume methods, but just being able to have something that reads the JSON, and then automatically creates all of the data elements in a Python class definition would be great.

For example, given this JSON (from a file or stream or wherever):

{
    "type": "software",
    "id": "software--a1b2c3d4-5678-90ab-cdef-12345example",
    "created": "2015-12-21T19:59:11Z",
    "modified": "2015-12-21T19:59:11Z",
    "name": "Microsoft Word",
    "cpe": "cpe:/a:microsoft:word:2013",
    "swid": "com.microsoft:word:2013",
    "languages": ["en"],
    "vendor": "Microsoft",
    "version": "2013"
}

Something that would read that and produce a Python class definition to hold that kind of data similar to the following.

class Software:
    def __init__(self, id, created, modified, name, cpe, swid, languages, vendor, version):
        self.type = "software"
        self.id = id
        self.created = created
        self.modified = modified
        self.name = name
        self.cpe = cpe
        self.swid = swid
        self.languages = languages
        self.vendor = vendor
        self.version = version

    def to_json(self):
        return {
            "type": self.type,
            "id": self.id,
            "created": self.created.strftime("%Y-%m-%dT%H:%M:%SZ"),
            "modified": self.modified.strftime("%Y-%m-%dT%H:%M:%SZ"),
            "name": self.name,
            "cpe": self.cpe,
            "swid": self.swid,
            "languages": self.languages,
            "vendor": self.vendor,
            "version": self. Version
        }

Does such a tool or method exist? And if so, what would that be?

Most of what I’ve found searching around requires you to have a class definition already defined, and the methods available deserialize JSON into the instances of the class you already have. I’m looking to create the class definitions based on the JSON.

I’ve looked at warlock, and valideer a while ago but they don’t get the job done.

2

Answers


  1. This may not be entirely what you want, but you can try this for your problem:

    import json
    
    json_data = json.load(open('test.json', 'r'))
    
    class AutoGeneratedVariables:
        def __init__(self,  **kwargs):
            for key in kwargs.keys():
                setattr(self, key, kwargs[key])
    
        def get_all_attrs(self):
            print(self.__dict__)
    
    AutoGeneratedVariables(**json_data).get_all_attrs()
    

    You should get the following output for your answer:

    {'type': 'software', 'id': 'software--a1b2c3d4-5678-90ab-cdef-12345example', 'created': '2015-12-21T19:59:11Z', 'modified': '2015-12-21T19:59:11Z', 'name': 'Microsoft Word', 'cpe': 'cpe:/a:microsoft:word:2013', 'swid': 'com.microsoft:word:2013', 'languages': ['en'], 'vendor': 'Microsoft', 'version': '2013'}
    

    If you try to print self.name it will give you ‘Microsoft Word’.

    Hope this answers your question.

    Login or Signup to reply.
  2. The json.load function accepts an object_hook parameter which allows you to customize what sort of Python value JSON objects are converted to.

    If you simply want objects with attributes rather than a dictionary with keys, you can use a SimpleNamespace:

    import json
    from types import SimpleNamespace
    
    json_data = '{"foo": {"bar": 10}, "baz": 20}'
    
    data = json.loads(
        json_data,
        object_hook=lambda d: SimpleNamespace(**d))
    
    print(data.foo.bar)
    print(data.baz)
    

    If you also want to parse and format dates, you could do that in your object_hook function as well, but you would need some way to specify the schema to know which fields should be converted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search