Search code examples
jsonrustserde-json

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?


Solution

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