Deserialize a json string to an object in python

后端 未结 12 2449
囚心锁ツ
囚心锁ツ 2020-11-28 05:01

I have the following string

{\"action\":\"print\",\"method\":\"onData\",\"data\":\"Madan Mohan\"}

I Want to deserialize to a object of cla

12条回答
  •  甜味超标
    2020-11-28 05:31

    pydantic is an increasingly popular library for python 3.6+ projects. It mainly does data validation and settings management using type hints.

    A basic example using different types:

    from pydantic import BaseModel
    
    class ClassicBar(BaseModel):
        count_drinks: int
        is_open: bool
     
    data = {'count_drinks': '226', 'is_open': 'False'}
    cb = ClassicBar(**data)
    >>> cb
    ClassicBar(count_drinks=226, is_open=False)
    

    What I love about the lib is that you get a lot of goodies for free, like

    >>> cb.json()
    '{"count_drinks": 226, "is_open": false}'
    >>> cb.dict()
    {'count_drinks': 226, 'is_open': False}
    

提交回复
热议问题