Error when traversing a json



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)?;

fn main() {
    let profiles = get_profile().unwrap();

        for element in profiles.as_array().iter() {
        println!("the value is: {}", element["age"]);



λ 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\
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.