Life is Really Short, Have Your Life!!



How to convert JSON data into a Python object? - Stack Overflow


import json
j = json.loads(your_json)
u = User(**j)


from typing import List, Optional

from pydantic import BaseModel

class Item(BaseModel):
    item_id: int
    item_name: str
    thumbnail: str
    description: str
    x_list: Optional[List[str]]
    maker: Optional[Maker]

class Maker(BaseModel):
    uuid: str
    name: str
    furigana: str
    email: str
    zipcode: str
    address: str
    building: str
    tel: str
    fax: str
# fastapi
async def fetch_item():
    import os
    base = os.path.dirname(os.path.abspath(__file__))
    with open(f'{base}/json/sample.json') as f:
        df = json.load(f)
        result = [Item(**x) for x in df] #これでオブジェクトに型変換できる
    return result