Error when traversing a json

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

Any help please, thanks.

The as_array() method returns an Option, of which the iterator yields the single contained element, which is itself a &Vec, so the element is not actually an element of the vector, it is the vector itself.

1 Like

How to modify the code?

You have to decide what to do if profiles is not an array, the change will depend on this.

You need to remove the layer of Option, preferably by pattern matching it and handling the case where it's None. In order to try if the rest of your code works, you can provide JSON that is guaranteed to contain an array in the correct place and simply unwrap() the option. This shouldn't be used lightly though – it will panic if the option is None (i.e. when the value doesn't contain an array).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.