Deserialize a json string to an object in python

后端 未结 12 2445
囚心锁ツ
囚心锁ツ 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:24

    Another way is to simply pass the json string as a dict to the constructor of your object. For example your object is:

    class Payload(object):
        def __init__(self, action, method, data, *args, **kwargs):
            self.action = action
            self.method = method
            self.data = data
    

    And the following two lines of python code will construct it:

    j = json.loads(yourJsonString)
    payload = Payload(**j)
    

    Basically, we first create a generic json object from the json string. Then, we pass the generic json object as a dict to the constructor of the Payload class. The constructor of Payload class interprets the dict as keyword arguments and sets all the appropriate fields.

提交回复
热议问题