New to python, I can’t find what I want to search for. For example, read data from a json configuration file, then create class objects based on the data, and then call the methods of these objects. The data of this json configuration file can be set freely. There may be a set of data corresponding to an object of a class. There may also be three sets of data corresponding to three classes of objects.
How to write code to read this json data and create an object of the class?
For example
Class targetobject(object):
def __init__(attr1,attr2): def func1(self): ...
And our json data is... "object1":{"attr1":"dawdad","attr2":"dwagfreg"},"object2":{"attr1":"45324523", "attr2":"45634"},
As for the actual data, it may not be called object1 object2, it may be another name. And after I want to read this json file, create an object of the class and assign it to the data in json
The poster wants to create objects dynamically. Can be created with exec
output dawdad
You can also use type to create
When creating a class in Python, it is not necessary to provide all members (that is to say, all Python objects are not fixed)
eg.
So just read Json and add the corresponding data members in Json to any object
It sounds like the poster wants this kind of structure:
If it is a configuration file, it is recommended to use toml (https://github.com/toml-lang/...
Install python toml and you can use it.
Actually, I think you want to turn the
json
data in the file into an operable object, just like adictionary
... Let’s see if thejson
library meets the requirements: