简体   繁体   English

将有向图转换为Json文件python

[英]convert directed graph to Json file python

I'm Converting dictionary to a directed graph then I'm trying saving that graph as a JSON file in this code: 我正在将字典转换为有向图,然后尝试在此代码中将该图另存为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()

Its giving me an error at json.dump as 它在json.dump给我一个错误

Object of type 'DirectedGraph' is not JSON serializable “ DirectedGraph”类型的对象不可JSON序列化

How can I fix it? 我该如何解决?

The JSON module only knows how to serialize basic python types. JSON模块仅知道如何序列化基本python类型。 while using dump to add Object in this case (graph), Serialize arbitrary Python objects to JSON using dict 在这种情况下使用转储添加对象(图形)时, 使用dict将任意Python对象序列化为JSON

I've just edited my code to: 我刚刚将代码编辑为:

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

and it worked perfictly. 而且效果很好。

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

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