Reputation: 7381
Say I have a string "[A,B,C]" and I want to convert it into a list [A,B,C], I have googled around and I know I should use pickle, but it seems that before I pickle.loads
I seems to have to pickle.dumps
the object, is that true? If yes, how can I walk around this?
Upvotes: 1
Views: 1811
Reputation: 54242
pickle.dumps
is the function that serializes Python objects into Pickle strings, and pickle.loads
converts serialized Pickle strings into Python objects. You're basically asking how to deserialize an object which isn't serialized. The answer is that you can't.
However, bikeshredder is correct -- your string is already in JSON's serialization format, so you can use json.loads
.
Upvotes: 2
Reputation: 7487
The string "[A,B,C]" is neither a pickle format nor any other serialization format known to me. It is not Python code either.
If you just want to deserialize some data (e.g. read from a file) I would recommend to use JSON. It is easy to write, fast to parse and is a well established standard.
>>> import json
>>> data_json = '["A", "B", "C"]'
>>> data = json.loads(data_json)
>>> data
[u'A', u'B', u'C']
>>> data_json = json.dumps(data)
>>> data_json
'["A", "B", "C"]'
Upvotes: 1