简体   繁体   中英

Deserialising JSON in a different format - Serde_JSON

I am trying to read JSON from a file in Rust which has the following dimensions:

{
    "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."
}

I want to store each word and its description in a vector (this is for a hangman game). I can read the file if the file is formatted like this:

[
    {
        "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."
    }
]

I do this using the following code:

#[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(())
}

However I am trying to figure out how to keep the original formatting of the JSON file without converting it to word & description in the 2nd JSON example.

Is there a way to use the existing JSON format or will I need to reformat it?

If you want to save allocations and iterations, you can accomplish this with a custom deserialize implementation instead:

#[macro_use]
extern crate serde_derive;

use std::fmt;
use serde::de::{Deserialize, Visitor, MapAccess};

#[derive(Deserialize, Debug)]
struct Word {
    word: String,
    description: String,
}

#[derive(Debug)]
struct WordList {
    list: Vec<Word>,
}

#[derive(Debug)]
struct WordListVisitor;

impl<'de> Visitor<'de> for WordListVisitor {
    type Value = WordList;
    
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a string->string map")
    }
    
    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
        let mut list = Vec::with_capacity(access.size_hint().unwrap_or(0));
    
        while let Some((word, description)) = access.next_entry()? {
            list.push(Word { word, description });
        }
        
        Ok(WordList { list })
    }
}


impl<'de> Deserialize<'de> for WordList {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_map(WordListVisitor)
    }
}

fn main() -> serde_json::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: WordList = serde_json::from_str(data)?;
    println!("{:#?}", words);
    Ok(())
}

playground

You can collect the map into a HashMap or BTreeMap and then use its key-value pairs to make a vector of words.

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(())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM