I know this looks like Frequency Ask Question mainly this question: How to convert JSON data into a Python object?
I will mention most voted answer:
import json
from types import SimpleNamespace
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
print(x.name, x.hometown.name, x.hometown.id)
Based on that answer, x
is object. But it's not object from model. I mean model that created with class. For example:
import json
from types import SimpleNamespace
class Hometown:
def __init__(self, name : str, id : int):
self.name = name
self.id = id
class Person: # this is a model class
def __init__(self, name: str, hometown: Hometown):
self.name = name
self.hometown = hometown
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
x = Person(what should I fill here?) # I expect this will automatically fill properties from constructor based on json data
print(type(x.hometown)) # will return Hometown class
I'm asking this is simply because my autocompletion doesn't work in my code editor if I don't create model class. For example if I type dot after object, it will not show properties name.
CodePudding user response:
This is how you can achieve that.
class Person: # this is a model class
def __init__(self, name: str, hometown: dict):
self.name = name
self.hometown = Hometown(**hometown)
x = Person(**json.loads(data))