Parsing a JSON into a Map in rust
Asked Answered
P

1

12

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.

Phyllotaxis answered 30/7, 2019 at 21:12 Comment(0)
C
11

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();
Cession answered 30/7, 2019 at 21:17 Comment(2)
Thank you for the quick response. Cloning solved the problem. I will accept ASAP.Phyllotaxis
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.Schweitzer

© 2022 - 2024 — McMap. All rights reserved.