Serde JSON From File
To retrieve JSON from a file using serde_json, we have to know the type of the JSON content first in order to properly transform it to a readable JSON object. So if you have something like the following.
{
"xUb9x8ij": {
"title": "Pocket Server",
"domain": "pocketserver.boil"
},
"tUbxx8ij": {
"title": "Pocket Server",
"domain": "pocketserver.boil"
}
}
The following type should work.
// derive(Debug, Serialize, Deserialize) here
struct AppInfo {
title: String,
domain: String,
}
type JsonMap = HashMap*lt*String, AppInfo*gt*;
use std::collections::HashMap;
And to retrieve JSON from a buffer or a file, we could use this function.
use serde::Deserialize;
use serde::Serialize;
use serde_json::Result;
fn read_json_from_fileP: AsRef*lt*Path*gt**gt*(path: P) -> Result*lt*JsonMap*gt* {
// Open the file in read-only mode with buffer.
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
// Read the JSON contents of the file as an instance of `AppInfo`.
let u = serde_json::from_reader(reader)?;
// Return the `AppInfo`.
Ok(u)
}
Thanks to brotskydotcom for the JSON type.
// https://github.com/serde-rs/json/issues/417#issuecomment-723531120
More Logs