Deserialize a json string to an object in python

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

    I thought I lose all my hairs for solving this 'challenge'. I faced following problems:

    1. How to deserialize nested objects, lists etc.
    2. I like constructors with specified fields
    3. I don't like dynamic fields
    4. I don't like hacky solutions

    I found a library called jsonpickle which is has proven to be really useful.

    Installation:

    pip install jsonpickle
    

    Here is a code example with writing nested objects to file:

    import jsonpickle
    
    
    class SubObject:
        def __init__(self, sub_name, sub_age):
            self.sub_name = sub_name
            self.sub_age = sub_age
    
    
    class TestClass:
    
        def __init__(self, name, age, sub_object):
            self.name = name
            self.age = age
            self.sub_object = sub_object
    
    
    john_junior = SubObject("John jr.", 2)
    
    john = TestClass("John", 21, john_junior)
    
    file_name = 'JohnWithSon' + '.json'
    
    john_string = jsonpickle.encode(john)
    
    with open(file_name, 'w') as fp:
        fp.write(john_string)
    
    john_from_file = open(file_name).read()
    
    test_class_2 = jsonpickle.decode(john_from_file)
    
    print(test_class_2.name)
    print(test_class_2.age)
    print(test_class_2.sub_object.sub_name)
    

    Output:

    John
    21
    John jr.
    

    Website: http://jsonpickle.github.io/

    Hope it will save your time (and hairs).

提交回复
热议问题