Aurelia Peters
Aurelia Peters

Reputation: 2209

Translating JSON object into HashMap with serde_json

I'm trying to parse a JSON object into a HashMap in Rust using serde_json. With the following code, I get the error:

error[E0507]: cannot move out of index of `Value`

How do I get that Value into my HashMap?

use serde_json::{Result, Value};
use std::collections::HashMap;

fn main() {

  let variables_json = r#"{
    "awayTeamAbbrev": "DAL",
    "homeTeamAbbrev": "TB",
    "gameInstanceUid": "cbs-nfl-pickem-challenge",
    "sportType": "NFL",
    "weekNumber": 1
  }"#;
  let keys = vec!["sportType","weekNumber"];
  dbg!(json_to_hashmap(&variables_json, keys));
    
}  

fn json_to_hashmap(json: &str, keys: Vec<&str>) -> Result<HashMap<String, Value>> {
    let lookup: Value = serde_json::from_str(json).unwrap();
    let mut map = HashMap::new();
    for key in keys {
        let varname = key.to_owned();
        let value = lookup[&varname];
        map.insert(varname, value);
    }
    Ok(map)

}

Upvotes: 7

Views: 12981

Answers (1)

Jmb
Jmb

Reputation: 23264

You can get a HashMap<String, Value> directly from serde_json::from_str, then use remove_entry to take the values out without cloning:

fn json_to_hashmap(json: &str, keys: Vec<&str>) -> Result<HashMap<String, Value>> {
    let mut lookup: HashMap<String, Value> = serde_json::from_str(json).unwrap();
    let mut map = HashMap::new();
    for key in keys {
        let (k, v) = lookup.remove_entry (key).unwrap();
        map.insert(k, v);
    }
    Ok(map)
}

Playground

Upvotes: 12

Related Questions