test2.json
[
{"name":"Lucy","age":18,"achievement":[95,86.5,90]},
{"name":"Lily","age":19,"achievement":[92.5,89,91]},
{"name":"Jack","age":20,"achievement":[93,90,93.5]}
]
main.rs
use std::fs::File;
use std::io::BufReader;
use serde_json::{Result as SResult, Value};
fn get_profile() -> SResult<Value> {
let file = File::open("test2.json").expect("file should open read only");
let reader = BufReader::new(file);
let mut v: Value = serde_json::from_reader(reader)?;
Ok(v.take())
}
fn main() {
let profiles = get_profile().unwrap();
for element in profiles.as_array().iter() {
println!("the value is: {}", element["age"]);
}
}
error:
λ cargo run
Compiling hello-rust v0.1.0 (D:\workspace\rust-projects\hello-rust)
error[E0277]: the type `[Value]` cannot be indexed by `&str`
--> src\main.rs:20:38
|
20 | println!("the value is: {}", element["age"]);
| ^^^^^^^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `SliceIndex<[Value]>` is not implemented for `&str`
= note: required because of the requirements on the impl of `std::ops::Index<&str>` for `Vec<Value>`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `hello-rust` due to previous error
上面的遍历json,应该怎么修改才对。请大佬指导一下
1
共 4 条评论, 1 页
评论区
写评论vscode用这个插件可以很好的看到类型 rust-analyzer
yes
--
👇
Grobycn:
profiles.as_array()
返回的是Option<Vec<&Value>>
,不是Vec<&Value>
for element in profiles.as_array().unwrap().iter() {
println!("{:?}",element.get("age").unwrap());
}
profiles.as_array()
返回的是Option<Vec<&Value>>
,不是Vec<&Value>