将有向图转换为 Json 文件 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 上给了我一个错误,因为

类型为"DirectedGraph"的对象不可 JSON 序列化

我该如何解决它?

JSON模块只知道如何序列化基本的 python 类型。 在这种情况下使用转储添加对象(图(, 使用dict将任意 Python 对象序列化为 JSON

我刚刚将我的代码编辑为:

with open(f'{string_input}.json', 'w') as output_file:
json.dump(graph.__dict__, output_file)

它巧妙地工作了。

最新更新