Search code examples
pythoncharacter-encodingpickle

Convert Object Serialized with Pickle to String in Python


I am attempting to convert the output of pickle.dumps into a string, though I am met with an error message relating to string encoding.

Code with Error:

import pickle

class TestClass:
    def __init__(self, number):
        self.number = number

t1 = TestClass(14)
s1 = pickle.dumps(t1)
str_version = s1.decode('utf-8', 'backslashreplace')
print(pickle.loads(str_version.encode('utf-8', 'backslashreplace')))

Error:

Traceback (most recent call last):
  File "C:\Users\ketha\Downloads\python_testing.py", line 11, in <module>
    print(pickle.loads(str_version.encode('utf-8', 'backslashreplace')))
_pickle.UnpicklingError: invalid load key, '\x5c'.

I think this is because when I convert it to a string, it converts \x5c (for example) to \\x5c and doesn't undo this during decoding. How could I undo this?


Solution

  • I got some code working. Code:

    import pickle
    import sys
    
    class TestClass:
        def __init__(self, number):
            self.number = number
    
    t1 = TestClass(14)
    s1 = pickle.dumps(t1)
    str_version = s1.decode('unicode_escape')
    decoded = pickle.loads(str_version.encode('utf-8', 'unicode_escape').replace(b'\xc2', b''))
    print(decoded.number)