Search code examples
rustserde-json

Reading an array of strings from a file in Rust


I have the following JSON:

[
    "String1",
    "String2",
    "String3"
]

I'm trying to read it in Rust with serde_json like this:

serde_json::from_str::<Vec<String>>("file_path").unwrap();

However, I get the following error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("expected value", line: 1, column: 1)'

The full stack trace isn't giving me much info. I tried converting it into a HashMap of the form <String, Vec<String>>, as well as using custom serializer types, and still get the same error repeatedly. Any ideas what might be going on here?


Solution

  • serde_json::from_str::<Vec<String>>("file_path").unwrap();
                             //         ^^^^^^^^^^^
    

    If that is your code as-is. then it won't work. from_str expects a &str with JSON in it, not a file path, e.g.

    serde_json::from_str::<Vec<String>>(r#"["String1", "String2"]"#).unwrap();
    

    Instead, open the file to get a Read and then use serde_json::from_reader.

    See the example in the documentation for more information.