小编Pra*_*rad的帖子

如何使用 serde 在 Rust 中解析这个 JSON 文件?

我是 Rust 新手。我正在尝试解析 JSON 文件并将数据存储为 Rust 中的对象。

JSON 文件如下所示:

{
"comment": ["some comments"],
"data": [
    ["name", "line 1"],
    ["name", ["line 1", "line 2"]],
    ......
    ["name", "line 1"]
]
//(The line where the error is coming)

}
Run Code Online (Sandbox Code Playgroud)

我做了这样的结构:

#[derive(Debug, Deserialize)]
struct my_data {
    comment: String,
    data: Vec<sub_data>,
}
#[derive(Debug, Deserialize)]
struct sub_data {
    name: String, 
    pattern: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试了这段代码,但出现错误:

Error("missing field `Comment`", line: 1381, column: 1)',
Run Code Online (Sandbox Code Playgroud)

代码:

pub fn read_json () {
    let path = "./src/my_file.json";
    let data = fs::read_to_string(path).expect("Unable to …
Run Code Online (Sandbox Code Playgroud)

json rust serde

2
推荐指数
1
解决办法
1120
查看次数

标签 统计

json ×1

rust ×1

serde ×1