将有向图转换为 Json 文件 python
convert directed graph to Json file python
我正在将字典转换为有向图,然后尝试将该图保存为以下代码中的 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 类型。在这种情况下使用转储添加对象时(图表),Serialize arbitrary Python objects to JSON using dict
我刚刚将我的代码编辑为:
with open(f'{string_input}.json', 'w') as output_file:
json.dump(graph.__dict__, output_file)
而且效果很好。
我正在将字典转换为有向图,然后尝试将该图保存为以下代码中的 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 类型。在这种情况下使用转储添加对象时(图表),Serialize arbitrary Python objects to JSON using dict
我刚刚将我的代码编辑为:
with open(f'{string_input}.json', 'w') as output_file:
json.dump(graph.__dict__, output_file)
而且效果很好。