Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Python, the equivalent of Go Struct is a Class. And the equivalent of Unmarshal in Python is Deserialization which can be done using the json module or the pickle module.

The process of Deserialization involves taking structured data like JSON or binary data in the case of Pickle, and converting it into a Python object. The resulting object can then be used to access the data in a more convenient way.

In Python, you can define a Class with attributes to represent the structured data you want to deserialize. Then, you can use the load() method in the json module or the load()/loads() methods in the pickle module to create an instance of that Class from the structured data.

Example code using the json module:

import json

class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

json_data = '{"name": "John", "age": 30, "city": "New York"}'

person = json.loads(json_data, object_hook=lambda d: Person(**d))
print(person.name)   # Output: John
print(person.age)    # Output: 30
print(person.city)   # Output: New York

Example code using the pickle module:

import pickle

class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

pickle_data = b'\x80\x04\x95(\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x04name\x94\x8c\x04John\x94\x8c\x03age\x94K\x1e\x8c\x04city\x94\x8c\x08New York\x94u.'

person = pickle.loads(pickle_data)
print(person.name)   # Output: John
print(person.age)    # Output: 30
print(person.city)   # Output: New York