如何在数据库中存储字典/列表?
如果我有一个充满嵌套内容的字典,如何将其作为字符串存储在数据库中?然后,当我准备好解析时将其转换回字典?
编辑:我只想将其转换为字符串......然后再转换回字典。
If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
选项:
1) Pickling
2) XML
3) JSON
其他我确定。它与可移植性对您的意义有很大关系。
Options:
1) Pickling
2) XML
3) JSON
others I am sure. It has a lot to do on how much portability means to you.
为什么不使用 pickle 模块中的一些序列化/反序列化?
http://docs.python.org/library/pickle.html
Why don't you use some serialization/deserialization from pickle module ?
http://docs.python.org/library/pickle.html
最好,根据您指定的条件:
-1
确保最有效的序列化并生成二进制 字符串(任意字节字符串)。如果您需要一个 ascii 字符串(因为例如将会发生一些 Unicode 转码,并且您无法将字段的类型从TEXT
切换为BLOB< /code>),避免使用
-1
,但效率会降低。无论哪种情况,要稍后从字符串中获取字典,
Best, under your stated conditions:
the
-1
ensures the most efficient serialization and produces a binary string (arbitrary string of bytes). If you need an ascii string (because e.g. some Unicode transcoding is going to happen and you can't switch the field's type from, say,TEXT
toBLOB
), avoid the-1
, but you'll then be less efficient.To get the dict back later from the string, in either case,
有许多序列化方法,JSON 是可读的、相当紧凑的、本地支持的并且可移植的。我更喜欢它而不是 pickle,因为后者可以执行任意代码并可能引入安全漏洞,而且还因为它的可移植性。
根据数据的布局,您还可以使用 ORM 将数据直接映射到数据库结构中。
There are any number of serialization methods out there, JSON is readable, reasonably compact, supported natively, and portable. I prefer it over pickle, since the latter can execute arbitrary code and potentially introduce security holes, and because of its portability.
Depending on your data's layout, you may also be able to use your ORM to directly map the data into database constructs.
您有两个选择
使用标准序列化格式(json、xml、yaml...)
使用 cPickle:
You have two options
use a standard serialization format (json, xml, yaml, ...)
use cPickle: