msgpack 以二进制形式获取字符串数据

msgpack gets string data back as binary

an answer ( 中给出了如何将数据转储到磁盘并读回。

我必须修改那里给出的答案(即:添加 "b" 读写选项)才能使其正常工作。但是从磁盘读取的数据还是不一样,因为现在从磁盘读取的字符串似乎是二进制的。

我怎样才能避免这种情况?

这是我改编的代码:

import msgpack

# Define data

data = {'a list': [1, 42, 3.141, 1337, 'help'],
        'a string': 'bla',
        'another dict': {'foo': 'bar',
                         'key': 'value',
                         'the answer': 42}}

# Write msgpack file
with open('data.msgpack', 'wb') as outfile:
    msgpack.pack(data, outfile)

# Read msgpack file
with open('data.msgpack', "rb") as data_file:
    # data_loaded = json.load(data_file)
    data_loaded = msgpack.unpack(data_file)

print(data == data_loaded)
print("data:", data)
print("data_loaded:", data_loaded)

输出:

False
data: {'a list': [1, 42, 3.141, 1337, 'help'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}
data_loaded: {b'a list': [1, 42, 3.141, 1337, b'help'], b'a string': b'bla', b'another dict': {b'foo': b'bar', b'key': b'value', b'the answer': 42}}

版本 (msgpack._version.py) 似乎是:

version = (0, 6, 0)

在阅读时设置raw=False 就可以了。代码:

import msgpack

# Define data

data = {'a list': [1, 42, 3.141, 1337, 'help'],
        'a string': 'bla',
        'another dict': {'foo': 'bar',
                         'key': 'value',
                         'the answer': 42}}

# Write msgpack file
with open('data.msgpack', 'wb') as outfile:
    msgpack.pack(data, outfile, )

# Read msgpack file
with open('data.msgpack', "rb") as data_file:
    # data_loaded = json.load(data_file)
    data_loaded = msgpack.unpack(data_file,raw=False)

print(data == data_loaded)
print("data:", data)
print("data_loaded:", data_loaded)

输出:

True
data: {'a list': [1, 42, 3.141, 1337, 'help'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}
data_loaded: {'a list': [1, 42, 3.141, 1337, 'help'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}