Skip to content

Add a standalone implementation for parse_raw similar to parse_file_as and parse_obj_as #1812

@mastern2k3

Description

@mastern2k3

Feature Request

As described in the docs:

Pydantic includes a standalone utility function parse_obj_as that can be used to apply the parsing logic used to populate pydantic models in a more ad-hoc way. This function behaves similarly to BaseModel.parse_obj, but works with arbitrary pydantic-compatible types.

Enabling code such as this:

from typing import List

from pydantic import BaseModel, parse_obj_as

class Item(BaseModel):
    id: int
    name: str

item_data = [{'id': 1, 'name': 'My Item'}]

items = parse_obj_as(List[Item], item_data)
print(items)
#> [Item(id=1, name='My Item')]

This works if you have a given object () to start with, but if you have a raw string or bytes you are required to parse them first into an object.

Forcing you to write this:

import json

item_data = '[{"id": 1, "name": "My Item"}]'
item_data_obj = json.loads(item_data)

items = parse_obj_as(List[Item], item_data_obj)

Instead, I suggest a standalone parse function, similar to parse_obj_as but for raw data, enabling something like this:

import json

item_data = '[{"id": 1, "name": "My Item"}]'

items = parse_raw_as(List[Item], item_data)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions