13

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.

1 Answer 1

12

Since as_object returns a reference and you need an owned value, you will need to clone the map. Luckily Map provides a Clone implementation so you can do this:

let obj: Map<String, Value> = parsed.as_object().unwrap().clone();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick response. Cloning solved the problem. I will accept ASAP.
Likewise, you might consider updating your read_config function signature to pub fn read_config(path: &str) -> Result<Map<String, Value>, Box<dyn Error>> to satisfy the compiler's warning message: warning: trait objects without an explicit 'dyn' are deprecated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.