【问题标题】:How to visualize graph-like json如何可视化类似图形的 json
【发布时间】:2021-12-04 23:06:25
【问题描述】:

我有如下 json 文件

{
    "A": {
            "field1": "X",
            "field2": "Y",
            "next": ["B"]
    },
    "B": {
            "field1": "X",
            "field2": "Y",
            "next": ["C", "D"]
    },
    "C": {
            "field1": "X",
            "field2": "Y",
            "next": ["A"]
    },
    "D": {
            "field1": "X",
            "field2": "Y",
            "next": ["C", "E"]
    },
    "E": {
            "field1": "X",
            "field2": "Y",
            "next": ["C", "D"]
    }

}

json 中的每个键都是图的一个节点,next 字段中是连接的节点。

我正在寻找一个简单的解决方案来可视化这样的 json。 在示例中,边是 A -> B、B -> C、B -> D 等等。

提前致谢。

【问题讨论】:

  • 读取 json,转换为 .dot 格式,然后运行 ​​graphviz 来创建可视化。 graphviz.org

标签: graph graph-visualization


【解决方案1】:

总体思路是

  • 读取 JSON 文件并将链接存储在图形数据结构中
  • 读取图形数据结构,写入graphviz点格式文本文件
  • 运行 graphviz dot 应用程序将点格式文本文件转换为 PMG 图形文件
  • 显示 PNG 文件

应用到您的示例文件的这个过程给出了

这是将 JSON 文件读入PathFinder 图论引擎的 C++ 代码

    // read  JSON into property tree
    boost::property_tree::ptree tree;
    read_json(myFile, tree);

    // loop over source nodes
    for (auto &src : tree)
    {
        // loop over destination nodes
        for (auto &dst : tree.get_child(src.first).get_child("next"))
        {
            // add link between source and destination
            myFinder.addLink(src.first, dst.second.data());
        }
    }

这是从路径查找器图形结构转换为点格式文本的 C++ 代码

        std::stringstream f;
        f << "graph G {\n";
        
        // loop over nodes
        for (auto n : nodes())
        {
            f << n.second.myName
              << " [ penwidth = 3.0 ];\n";
        }

        // loop over links
        for (auto &e : links())
        {
            f << node(e.first.first).myName << "->"
              << node(e.first.second).myName;
              << "\n";
        }

        f << "}\n";
        return f.str();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2015-08-21
    • 2010-10-08
    相关资源
    最近更新 更多