1

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.

1

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

4 Comments

print(x.hometown.id) has return error 'dict' object has no attribute 'id'
print(x.hometown['id']) this will return 123 no error. I expect I can access id with dot instead of square bracket.
You can do it it like this there is no problem: x.hometown.id
Okay my fault I didn't see you modified Person class in hometown property.

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.