gpt4 book ai didi

json - 以不同的格式反序列化 JSON - Serde_JSON

转载 作者:行者123 更新时间:2023-12-02 16:01:10 25 4
gpt4 key购买 nike

我正在尝试从具有以下维度的 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 格式,或者我需要重新格式化它吗?

最佳答案

您可以将 map 收集到 HashMapBTreeMap 中,然后使用它的键值对来制作单词向量。

fn main() -> Result<()> {
let data = r#"{
"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."
}"#;
let words: std::collections::BTreeMap<String, String> = serde_json::from_str(data)?;
let words = words
.into_iter()
.map(|(word, description)| Word { word, description })
.collect::<Vec<_>>();
println!("{:#?}", words);
Ok(())
}

关于json - 以不同的格式反序列化 JSON - Serde_JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70656234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com