我正在尝试从 Rust 中的文件读取 JSON,该文件具有以下维度:
{
"DIPLOBLASTIC":"Characterizing the ovum when it has two primary germinallayers.",
"DEFIGURE":"To delineate. [Obs.]These two stones as they are here defigured. Weever.",
"LOMBARD":"Of or pertaining to Lombardy, or the inhabitants of Lombardy.",
"BAHAISM":"The religious tenets or practices of the Bahais."
}
我想将每个单词及其描述存储在一个向量中(这是一个刽子手游戏)。如果文件格式如下,我可以读取文件:
[
{
"word": "DIPLOBLASTIC",
"description": "Characterizing the ovum when it has two primary germinallayers."
},
{
"word": "DEFIGURE",
"description": "To delineate. [Obs.]These two stones as they are here defigured. Weever."
}
]
我使用以下代码执行此操作:
#[macro_use]
extern crate serde_derive;
use serde_json::Result;
use std::fs;
#[derive(Deserialize, Debug)]
struct Word {
word: String,
description: String,
}
fn main() -> Result<()> {
let data = fs::read_to_string("src/words.json").expect("Something went wrong...");
let words: Vec<Word> = serde_json::from_str(&data)?;
println!("{}", words[0].word);
Ok(())
}
但是,我试图弄清楚如何保留 JSON 文件的原始格式,而不将其转换为第二个 JSON 示例中的单词和描述。
有没有办法使用现有的 JSON 格式或者我需要重新格式化它?