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:
JavaScript
x
9
1
import json
2
from types import SimpleNamespace
3
4
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
5
6
# Parse JSON into an object with attributes corresponding to dict keys.
7
x = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
8
print(x.name, x.hometown.name, x.hometown.id)
9
Based on that answer, x
is object. But it’s not object from model. I mean model that created with class. For example:
JavaScript
1
19
19
1
import json
2
from types import SimpleNamespace
3
4
class Hometown:
5
def __init__(self, name : str, id : int):
6
self.name = name
7
self.id = id
8
9
10
class Person: # this is a model class
11
def __init__(self, name: str, hometown: Hometown):
12
self.name = name
13
self.hometown = hometown
14
15
16
data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
17
x = Person(what should I fill here?) # I expect this will automatically fill properties from constructor based on json data
18
print(type(x.hometown)) # will return Hometown class
19
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.
Advertisement
Answer
This is how you can achieve that.
JavaScript
1
8
1
class Person: # this is a model class
2
def __init__(self, name: str, hometown: dict):
3
self.name = name
4
self.hometown = Hometown(**hometown)
5
6
7
x = Person(**json.loads(data))
8