将有向图转换为Json文件python

时间:2018-06-24 11:57:08

标签: python json directed-graph

我要将字典转换为有向图,然后尝试在此代码中将该图另存为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序列化

我该如何解决?

1 个答案:

答案 0 :(得分:0)

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)

它可以正常工作。