1. 程式人生 > >Rust CSV 轉換成 JSON 示例程式碼 (迭代實現)

Rust CSV 轉換成 JSON 示例程式碼 (迭代實現)

Rust的第三方庫 沒有CSV  轉換成 JSON 的方法,只能自己寫,例項程式碼如下:

fn converter2_json(header: &mut Vec<String>, rows: Vec<Vec<String>>) -> Vec<String> {
    let mut json_vet = vec![];
    for line in rows {
        let mut map = Map::new();
        read(&mut map, header, line);
        let ser = serde_json::to_string(&map).unwrap();
        // println!("{}", ser);
        json_vet.push(ser);
    }
    json_vet
}

fn read(map: &mut Map<String, JsonValue>, header: &mut Vec<String>, fields: Vec<String>) {
    for (i, field) in fields.iter().enumerate() {
        let mut column = &header[i];
        read_field(map, column.to_string(), field.to_string());
    }
}

fn read_field(map: &mut Map<String, JsonValue>, column: String, field: String) {
    if column.contains(":") {
        let column_list: Vec<&str> = column.splitn(2, ":").collect();
        let column_tmp = column_list[1].to_string();
        if !map.contains_key(column_list[0]) {
            let mut map_child = Map::new();
            map.insert(column_list[0].to_string(), json!(map_child));
        };
        let mut map_child_tmp = map
            .get_mut(&column_list[0].to_string())
            .unwrap()
            .as_object_mut()
            .unwrap();
        read_field(&mut map_child_tmp, column_list[1].to_string(), field);
    } else {
        map.insert(column.into(), json!(field));
    }
}