如何使Python类可序列化?
一个简单的课程:
class FileItem:
def __init__(self, fname):
self.fname = fname
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能得到输出:
>>> import json
>>> my_file = FileItem('/foo/bar')
>>> json.dumps(my_file)
TypeError: Object of type 'FileItem' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
没有错误(__CODE__)
我有这个真的如下破解代码将删除任何类型的数据结构的建造出来的循环引用dict,tuple和list对象.
import ast
def remove_circular_refs(o):
return ast.literal_eval(str(o).replace("{...}", 'None'))
Run Code Online (Sandbox Code Playgroud)
但我不喜欢它有多酷.这可以在不将数据结构转换为字符串表示的情况下完成吗?
这是一个用于测试的示例结构:
doc1 = {
"key": "value",
"type": "test1",
}
doc1["self"] = doc1
doc = {
'tags': 'Stackoverflow python question',
'type': 'Stackoverflow python question',
}
doc2 = {
'value': 2,
'id': 2,
}
remove_circular_refs(doc)
remove_circular_refs(doc1)
remove_circular_refs(doc2)
Run Code Online (Sandbox Code Playgroud)