igferne
igferne

Reputation: 339

Serizalize an array in Python

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)

Upvotes: 3

Views: 1492

Answers (4)

phynfo
phynfo

Reputation: 4938

... or perhaps just

str([1,2,4])

(if you dont necessarily need the data in json-format)

Upvotes: 0

Martin Stone
Martin Stone

Reputation: 13007

Doesn't MySQL let you store these pickled bytes in a blob?

Upvotes: 0

Javier
Javier

Reputation: 62613

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.

Upvotes: 1

gruszczy
gruszczy

Reputation: 42188

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

import json

v = [1, 2, 4]
s = json.dumps(v)

Upvotes: 5

Related Questions