-2

I'm trying to figure out what would be the best way to create classes in a dynamic manner based on the contents of a JSON file. So for example, here's a snippet from the JSON file:

{
"stuff": [{
        "name": "burger",
        "aka": ["cheeseburger", "hamburger"]
    },
    {
        "name": "fries",
        "aka": ["french fries", "potatoes"]
    },
    {
        "name": "meal",
        "items": [{
                "name": "burger",
                "value": "<burger>"
            },
            {
                "name": "fries",
                "value": "<fries>"
            }
        ]
    }

  ]
}

And now based on this JSON, I want classes that represent these objects. So for example, something like:

class Burger:
   def __init__(self):
   self.name = "burger"
   self.aka = ["cheeseburger", "hamburger"]

class Meal:
   def __init__(self):
   self.name = "meal"
   self.burger = Burger()
   self.fries = Fries()

So basically, based on that JSON, I want to be able to create classes that represent the same attributes and relationships that we see in the JSON. Any ideas about the best way to approach this would be appreciated!

12
  • I've done something similar with mapping FileMaker schema to classes. I just used the attributes to write out a file and then load that file. I imagine you could do pretty much the same. Commented Jun 14, 2019 at 5:02
  • Why would you want to write code in JSON? Why not just write the classes ... you know like a .py file Commented Jun 14, 2019 at 5:03
  • I imagine the JSON file already exists. Commented Jun 14, 2019 at 5:03
  • @rdas I'm not writing the code in JSON, the JSON already exists and the idea is to be able to use that to create the class Commented Jun 14, 2019 at 5:04
  • this question was asked before and answered: for example stackoverflow.com/questions/40336305/… Commented Jun 14, 2019 at 5:04

1 Answer 1

2

Assuming json variable contains your json data try this:

for d in json:
    name = d.pop('name')
    t = type(name, (object,), d)

What it does is to call type, which will create new type in python (exactly the same as if you did class name, which correct name set to content of name variable, with base class object and attributes in d. Variable t will contain class object you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.