1

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?

A. Gnias
  • 87
  • 3
  • 10

1 Answers1

4
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.

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • I now feel incredibly stupid, but am very thankful you could find this obvious mistake that I was banging my head against a wall about. – A. Gnias May 29 '22 at 14:26