[Python] 직렬화/역직렬화 (Serialization/Deserialization)
Serialization/Deserialization
Serialization | ||
Object | -> <- |
String (json) Byte Array (pickle) |
Deserialization |
json
module vs. pickle
module
json
: object <-> text serialization formatpickle
: object <-> binary serialization format
Conversion (Python Object <-> JSON)
- dict <-> object
- list, tuple <-> array
- str <-> string
- int, float, int- & float-derived Enums <-> number
- True <-> true
- False <-> false
- None <-> null
Serialization
Python object
toJSON formatted string
json.dumps(obj)
Python object
tobytes-like object
(bytes, bytearray, memoryview, …)
pickle.dumps(obj)
Deserialization
JSON formatted string
topython object
json.loads(data)
Bytes-like object
(bytes, bytearray, memoryview, …) topython object
pickle.loads(data)
Serialization in producer of kafka-python
- https://github.com/dpkp/kafka-python
Python object
->JSON formatted string
->bytes-like object
producer = KafkaProducer(bootstrap_servers='my-kafka:9092', value_serializer=lambda v: json.dumps(v).encode('utf-8'))
@staticmethod
def send(value, key):
producer.send('my-topic', value=value, key=key)
Deserialization in consumer of kafka-python
bytes-like object
->JSON formatted string
->Python object
consumer = KafkaConsumer('my-topic',
group_id='my-consumer-group-id',
bootstrap_servers='my-kafka:9092',
value_deserializer=lambda m: json.loads(m.decode('utf-8')))
@staticmethod
def subscribe():
for msg in MyKafkaConsumer.consumer:
print(msg.value)
Comments