简体   繁体   中英

JSON object mapper for Python

Basically I am automating the API in python, API returns JSON as response looks like below

In java I can validate the schema using POJO Model using Gson lib like as fallow -

GetCustomerModel - is my custom POJO class have so 3 inner classes.
GetCustomerModel body = new Gson().fromJson(response.getBody(),GetCustomerModel.class);

Is there any lib support in Python to do same, I mean conver json as custom python mapping object?

[{
    "businessUnit": {
        "code": "27888",
        "type": "LSCCC"
    },
    "timeWindows": [
        {
            "freeCapacity": true,
            "capacityTemplateIdentifier": "xxxxxxxxxxxx",
            "cutOff": "2020-11-30T17:00:00Z",
            "end": "2020-11-30T17:00:00Z",
            "maxCapacity": 0,
            "start": "2020-11-30T08:00:00Z",
            "timeWindowIdentifier": "yyyyyyyyyyyyyy",
            "tspId": "9900001"
        }
    ],
    "timeZone": "Europe/London"
}]

Python Model -

from dataclasses import dataclass
from datetime import datetime
from uuid import UUID
from typing import List


@dataclass
class BusinessUnit:
    code: int
    type: str


@dataclass
class TimeWindow:
    free_capacity: bool
    capacity_template_identifier: str
    cut_off: datetime
    end: datetime
    max_capacity: int
    start: datetime
    time_window_identifier: UUID
    tsp_id: int


@dataclass
class WelcomeElement:
    business_unit: BusinessUnit
    time_windows: List[TimeWindow]
    time_zone: str

My code -

result = from_dict(data_class=WelcomeElement, data=response.content)

Gives an error saying - "tuple indices must be integers or slices, not str"

The code below works:

Few points to improve:

  • use type hooks in order convert data types

  • deal with camelCase and snake_case

     from dataclasses import dataclass from datetime import datetime from uuid import UUID from typing import List from dacite import from_dict @dataclass class BusinessUnit: code: int type: str @dataclass class TimeWindow: free_capacity: bool capacity_template_identifier: str cut_off: str end: str max_capacity: int start: str time_window_identifier: str tsp_id: int @dataclass class WelcomeElement: business_unit: BusinessUnit time_windows: List[TimeWindow] time_zone: str data = [{ "business_unit": { "code": 27888, "type": "LSCCC" }, "time_windows": [ { "free_capacity": True, "capacity_template_identifier": "xxxxxxxxxxxx", "cut_off": "2020-11-30T17:00:00Z", "end": "2020-11-30T17:00:00Z", "max_capacity": 0, "start": "2020-11-30T08:00:00Z", "time_window_identifier": "yyyyyyyyyyyyyy", "tsp_id": 9900001 } ], "time_zone": "Europe/London" }] print('start') result = from_dict(data_class=WelcomeElement, data=data[0]) print(result)

    output

     start WelcomeElement(business_unit=BusinessUnit(code=27888, type='LSCCC'), time_windows=[TimeWindow(free_capacity=True, capacity_template_identifier='xxxxxxxxxxxx', cut_off='2020-11-30T17:00:00Z', end='2020-11-30T17:00:00Z', max_capacity=0, start='2020-11-30T08:00:00Z', time_window_identifier='yyyyyyyyyyyyyy', tsp_id=9900001)], time_zone='Europe/London')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM