繁体   English   中英

将有向图转换为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给我一个错误

“ DirectedGraph”类型的对象不可JSON序列化

我该如何解决?

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

我刚刚将代码编辑为:

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

而且效果很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM