Ask Your Question
0

What is the equivalent of Go Struct and Unmarshal in Python?

asked 2023-06-28 12:31:21 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-28 12:45:01 +0000

lakamha gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-28 12:31:21 +0000

Seen: 8 times

Last updated: Jun 28 '23