gpt4 book ai didi

正确处理 str/unicode 的 Python 保存序列化?

转载 作者:太空狗 更新时间:2023-10-30 01:10:07 24 4
gpt4 key购买 nike

除了 PyYAML,是否有任何安全的 Python 数据序列化库可以正确处理 unicode/str

例如:

>>> json.loads(json.dumps([u"x", "x"]))
[u'x', u'x'] # Both unicode
>>> msgpack.loads(msgpack.dumps([u"x", "x"]))
['x', 'x'] # Neither are unicode
>>> bson.loads(bson.dumps({"x": [u"x", "x"]}))
{u'x': [u'x', 'x']} # Dict keys become unicode
>>> pyamf.decode(pyamf.encode([u"x", "x"])).next()
[u'x', u'x'] # Both are unicode

请注意,我希望序列化程序是安全的(因此 picklemarshel 已被淘汰),PyYAML 是一个选项,但我不喜欢 YAML 的复杂性,所以我想知道是否有其他选择。

编辑:我的数据的性质似乎有些困惑。其中一些是 Unicode(例如,名称),其中一些是二进制(例如,图像)......因此混淆 unicodestr 的序列化库对我是一个混淆了 "42"42 的库。

最佳答案

也许只使用 Python 的 repr 来存储值并使用 ast 反序列化它.literal_eval 方法:

In [7]: ast.literal_eval (repr({"d": ["x", u"x"]}))
Out[7]: {'d': ['x', u'x']}

关于正确处理 str/unicode 的 Python 保存序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6991739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com