I'm quite a beginner in Rust, and just have encountered a problem with parsing JSON files. I tried using serde_json for the task. I know how to parse an ASCII file as a string, and how to parse its content as a Value
, but I need a Map<String, Value>
to iterate over the KVPs. I did not get too far, as I stumbled into a reference error. The method I tried is the following:
use std::fs;
use std::error::Error;
use serde_json::{Value, Map};
pub struct ConfigSerde;
impl ConfigSerde {
pub fn read_config(path: &str) -> Result<Map<String, Value>, Box<Error>> {
let config = fs::read_to_string(path)?;
let parsed: Value = serde_json::from_str(&config)?;
let obj: Map<String, Value> = parsed.as_object().unwrap();
Ok(obj)
}
}
Once I tried to run this code, the compiler threw the following error:
error[E0308]: mismatched types
--> src/config/serde.rs:11:39
|
11 | let obj: Map<String, Value> = parsed.as_object().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `serde_json::map::Map`, found reference
|
= note: expected type `serde_json::map::Map<std::string::String, serde_json::value::Value>`
found type `&serde_json::map::Map<std::string::String, serde_json::value::Value>`
How can I parse a JSON to a Map
in rust? I'm open to using alternative crates, although serde_json is the preferred one, as it seems the most robust of all.