使用 serde_json 将 JSON 对象转换为 HashMap
Translating JSON object into HashMap with serde_json
我正在尝试使用 serde_json
将 JSON 对象解析为 Rust 中的 HashMap。使用以下代码,我得到错误:
error[E0507]: cannot move out of index of `Value`
如何将 Value
放入我的 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)
}
可以直接从serde_json::from_str
得到一个HashMap<String, Value>
,然后用remove_entry
把值取出来,不用克隆:
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)
}
我正在尝试使用 serde_json
将 JSON 对象解析为 Rust 中的 HashMap。使用以下代码,我得到错误:
error[E0507]: cannot move out of index of `Value`
如何将 Value
放入我的 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)
}
可以直接从serde_json::from_str
得到一个HashMap<String, Value>
,然后用remove_entry
把值取出来,不用克隆:
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)
}