我正在尝试使用 ijson 而不是 json 以便能够有效地将字典转储到/从字符串(在内存中,而不是从文件中)转储/加载字典[1].
ijson 是否有任何类似于使用 json 进行标准转储/加载的示例?我见过的所有使用 ijson 的资源都只有文件示例。
[1] -- 字典被转换为字符串以便将它们存储在一个集合中
请您参考如下方法:
您可以实现这两个目标(无需使用 json 库即可实现字典到字符串和字符串到字典)。
让我们看看上面的例子:
import ast
di = {"a":2, "b": 3}
print (str(di))
>>> "{'a': 2, 'b': 3}"
print (type(str(di)))
>>> <class 'str'>
print (ast.literal_eval(str(di)))
>>> {'a': 2, 'b': 3}
print (type(ast.literal_eval(str(di))))
>>> <class 'dict'>
你有一个字典,为了把它变成字符串,你只需要将它转换成str。
如果你想将 str 返回给 dict,你可以使用 ast 库。
您可以阅读更多关于 ast.literal_eval 的信息
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display.
编辑:
经过进一步调查和关注this SO question似乎使用 json 会使您获得更快的结果(性能)。
查看附加链接中的 abarnert 答案,特别是:
Why is json.loads so much faster ?
Because Python literal syntax is a more complex and powerful language than JSON, it's likely to be slower to parse. And, probably more importantly, because Python literal syntax is not intended to be used as a data interchange format (in fact, it's specifically not supposed to be used for that), nobody is likely to put much effort into making it fast for data interchange.
import json
di = {"a":2, "b": 3}
print (json.dumps(di))
>>> '{"a": 2, "b": 3}'
print (type(json.dumps(di)))
>>> <class 'str'>
print (json.loads(json.dumps(di)))
>>> {'a': 2, 'b': 3}
print (type(json.loads(json.dumps(di))))
>>> <class 'dict'>
