turtle
turtle

Reputation: 8073

How to read JSON file with serde?

I'd like to read a JSON file and print its contents. I'm trying to use the serde crate but can't understand why this does not work:

use serde_json;
use std::fs;

fn main() {
    let path = "./src/input.json";
    let data = fs::read_to_string(path).expect("Unable to read file");
    let res = serde_json::from_str(&data);
    println!("{}", res)
}

The error I get is:

the trait `std::fmt::Display` is not implemented for `Result<_, serde_json::Error>`

How can I read a JSON file? Is there a better way to do this? I could not find a complete example in either the serde docs or elsewhere.

Upvotes: 7

Views: 9825

Answers (1)

user4815162342
user4815162342

Reputation: 154886

Your code has two issues. First, you didn't handle the error when parsing JSON. Just like read_to_string() returns a Result and you had to use expect() to get to the underlying value in case everything was fine, the same applies to serde_json::from_str().

Adding the missing expect() leads to the second issue, where the compiler complains:

error[E0282]: type annotations needed
 --> src/main.rs:7:9
  |
7 |     let res = serde_json::from_str(&data).expect("Unable to parse");
  |         ^^^ consider giving `res` a type

serde_json is strongly typed and can deserialize JSON into Rust types prepared by you. If you want to just inspect untyped JSON, you can use serde_json::Value (playground):

use serde_json;
use std::fs;

fn main() {
    let path = "./src/input.json";
    let data = fs::read_to_string(path).expect("Unable to read file");
    let res: serde_json::Value = serde_json::from_str(&data).expect("Unable to parse");
    println!("{}", res)
}

You can find this kind of example and more on the project page.

Upvotes: 11

Related Questions