我正在将字典转换为有向图,然后尝试将该图保存为JSON文件,代码如下:
def main():
g = {"a": ["d"],
"b": ["c"],
"c": ["b", "c", "d", "e"],
"d": ["a", "c"],
"e": ["c"],
"f": []
}
graph = DirectedGraph()
for key in g.keys():
graph.add(key)
elements = g[key]
for child in elements:
graph.add_edge(key, child)
with open('JJ.json', 'w') as output_file:
json.dump(graph, output_file)
main()
它给了我一个错误json.dump文件作为
Object of type 'DirectedGraph' is not JSON serializable
我怎样才能修好它?在
JSON模块只知道如何序列化基本的python类型。在本例中使用dump添加对象时,Serialize arbitrary Python objects to JSON using dict
我刚刚编辑了代码:
而且效果很好。在
相关问题 更多 >
编程相关推荐