从从 JSON 加载的 Vec<(String, String)> 创建 Petgraph 图

Create a Petgraph graph from a Vec<(String, String)> loaded from JSON

我正在尝试创建宠物图 Graph from JSON data. The JSON contains the edges of the graph, the key represents the starting vertex and the value is a list of adjacent vertices. It's possible to generate a graph with a vector of edges

我设法创建了 Vec<(String, String))>,但没有按预期创建 Vec<(&str, &str)>

extern crate petgraph;
extern crate serde_json;

use petgraph::prelude::*;
use serde_json::{Value, Error};

fn main() {
    let data = r#"{
      "A": [ "B" ],
      "B": [ "C", "D" ],
      "D": [ "E", "F" ]
    }"#;
    let json_value: Value = serde_json::from_str(data).unwrap();
    let mut edges: Vec<(String, String)> = vec![];
    if let Value::Object(map) = json_value {
        for (from_edge, array) in &map {
            if let &Value::Array(ref array_value) = array {
                for edge in array_value {
                    if let &Value::String(ref to_edge) = edge {
                        edges.push((from_edge.clone(), to_edge.clone()))
                    }
                }
            }
        }
    }
    // let graph = DiGraphMap::<&str, ()>::from_edges(edges);
    //             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct
    //             `std::string::String`, found &str

}

我尝试了不同的方法:

这里可能有更好的提取边缘的方法。

Change the graph type to DiGraphMap::<String, ()>, however it does not accept it.

A GraphMap 要求节点类型是可复制的。 String 未实施 Copy.

Transform a Vec<(String, String)> into a Vec<(&str, &str)>

如您链接的问题中所述,这是不可能的。您可以 做的是创建一个 second Vec&str 并引用原始 String

let a: Vec<(String, String)> = vec![("a".into(), "b".into())];

let b: Vec<(&str, &str)> = a.iter()
    .map(|&(ref x, ref y)| (x.as_str(), y.as_str()))
    .collect();

但是,在这种情况下不需要这样做。相反,将 JSON 数据读入建模地图的数据结构(我选择 BTreeMap)并将 String 留在那里。然后,您可以构建对那些 String 的引用对的迭代器,从中构建图形:

extern crate petgraph;
extern crate serde_json;

use petgraph::prelude::*;
use std::collections::BTreeMap;
use std::iter;

fn main() {
    let data = r#"{
      "A": [ "B" ],
      "B": [ "C", "D" ],
      "D": [ "E", "F" ]
    }"#;

    let json_value: BTreeMap<String, Vec<String>> =
        serde_json::from_str(data).unwrap();

    let edges = json_value
        .iter()
        .flat_map(|(k, vs)| {
            let vs = vs.iter().map(|v| v.as_str());
            iter::repeat(k.as_str()).zip(vs)
        });

    let graph: DiGraphMap<_, ()> = edges.collect();
}

I need to encapsulate this into a function

几乎不可能做到。由于 JSON 字符串包含 UTF-8 数据,Serde 允许您获取对原始输入字符串的引用。您需要记住,您的 graph 不能 input:

长寿
fn main() {
    let data = r#"{
      "A": [ "B" ],
      "B": [ "C", "D" ],
      "D": [ "E", "F" ]
    }"#;

    let graph = example(data);
}

fn example(data: &str) -> serde_json::Result<DiGraphMap<&str, ()>> {
    let json_value: BTreeMap<&str, Vec<&str>> = serde_json::from_str(data)?;

    let edges = json_value
        .into_iter()
        .flat_map(|(k, vs)| iter::repeat(k).zip(vs));

    Ok(edges.collect())
}