logger
logger

Reputation: 2053

How to convert JSON into instances of a custom class?

I am not sure if this question has been asked before but I can't find related custom mapping. Usually it is a direct JSON to object 1:1 mapping.

So here is my sample example:

class Test():
    id: str
    name: str
    msg: str

data = [
    {
        "id": "12345",
        "client": "test",
        "msg": "random"
    }, {
        "id": "54321",
        "client": "test-2",
        "msg": "random-2"
    }
]

So on above I have a JSON, I wanted to directly convert it to object I have on the first class. Note the "client" from the JSON becomes name.

So the final output when I do load the object it would become.

data = [
    {
        "id": "12345",
        "name": "test",
        "msg": "random"
    }, {
        "id": "54321",
        "name": "test-2",
        "msg": "random-2"
    }
]

Upvotes: 1

Views: 654

Answers (2)

daniboy000
daniboy000

Reputation: 1129

You can use Pydantic as well to define your class like showed bellow:

from pydantic import BaseModel

class User(BaseModel):
    id: str
    name: str
    msg: str

    def __init__(self, id: str, client: str, msg: str) -> None:
        super().__init__(id=id, name=client, msg=msg)

users = [
    {
        'id': '12345',
        'client': 'test',
        'msg': 'random',
    },
    {
        'id': '54321',
        'client': 'test-2',
        'msg': 'random-2',
    }
]

objects = [User(**user) for user in users]

print(objects)
# Output
[
   User(id='12345', name='test', msg='random'),
   User(id='54321', name='test-2', msg='random-2')
]

Upvotes: 2

Rafael Setton
Rafael Setton

Reputation: 397

class Test():
    def __init__(self, id, client, msg):
        self.id = id
        self.name = client
        self.msg = msg

data = [
    {
        "id": "12345",
        "client": "test",
        "msg": "random"
    }, {
        "id": "54321",
        "client": "test-2",
        "msg": "random-2"
    }
]

# unpack values from dict and pass in as arguments for Test.__init__()
objects = [Test(**item) for item in data] 

Upvotes: 3

Related Questions