将有向图转换为Json文件python

2024-09-29 23:31:47 发布

您现在位置: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

我怎样才能修好它?在


Tags: 文件keyinaddjsonchildforoutput
1条回答
网友
1楼 · 发布于 2024-09-29 23:31:47

JSON模块只知道如何序列化基本的python类型。在本例中使用dump添加对象时,Serialize arbitrary Python objects to JSON using dict

我刚刚编辑了代码:

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

而且效果很好。在

相关问题 更多 >

    热门问题