Search code examples
pydantic

pydantic v2 migrate json_loads, json_dumps


Pydantic v2 has dropped json_loads (and json_dumps) config settings (see migration guide)

However, there is no indication by what replaced them. Does anyone have pointers on these?


Solution

  • In Pydantic v2 those methods have been replaced by .model_dump_json() and .model_validate_json(). See the following example:

    from pydantic import BaseModel
    
    class Model(BaseModel):
        a: str
        b: str 
    
    
    m = Model(a="1", b="2")
    data = m.model_dump_json()
    print(type(data))
    
    m_new = Model.model_validate_json(data)
    print(type(m_new))
    

    Which prints:

    <class 'str'>
    <class '__main__.Model'>
    

    Dumping a model to a dict with json encoding instead, works like:

    from pydantic import BaseModel
    
    class Model(BaseModel):
        a: str
        b: str 
    
    
    m = Model(a="1", b="2")
    data = m.model_dump(mode="json")
    print(type(data))
    
    m_new = Model.model_validate(data)
    print(type(m_new))
    

    Which prints:

    <class 'dict'>
    <class '__main__.Model'>
    

    I hope this helps!