Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serizalize an array in Python

Tags:

python

mysql

I ´m trying to serialize an array in python to insert it on a database of MySQL... I try with pickle.dump() method but it returns byte... what can I use?? thanks!!

(I ´m working in python 3)

like image 856
igferne Avatar asked May 28 '26 23:05

igferne


2 Answers

You can try to use json to turn it into a string, like this:

import json

v = [1, 2, 4]
s = json.dumps(v)
like image 94
gruszczy Avatar answered May 31 '26 12:05

gruszczy


Pickle is a binary serialization, that's why you get a byte string.

Pros:

  • more compact
  • can express most of Python's objects.

Con's:

  • bytes can be harder to handle
  • Python only.

JSON is more universal, so you're not tied to reading data with Python. It's also mostly ASCII, so it's easier to handle. the con is that it's limited to numbers, strings, arrays and dicts. usually enough, but even datetimes have to be converted to string representation before encoding.

like image 42
Javier Avatar answered May 31 '26 13:05

Javier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!