Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON into a Map in rust

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.

like image 563
Gabor Farkas Avatar asked Jul 30 '19 21:07

Gabor Farkas


1 Answers

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();
like image 119
Luke B. Avatar answered Sep 20 '22 21:09

Luke B.