如何使用serde读取JSON文件?解决Display trait未实现报错
First, let's fix your immediate error. The problem is that serde_json::from_str returns a Result<T, serde_json::Error>, and you're trying to print this Result directly. Rust's Result type doesn't implement the Display trait by default (though it does implement Debug, so using println!("{:?}", res) would work as a quick hack, but that's not ideal for clean code).
Fixing the Immediate Error
Here's how to adjust your code to properly handle the Result and print the parsed JSON content:
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"); // Parse the JSON into a generic Value type (works for any JSON structure) let res: serde_json::Value = serde_json::from_str(&data) .expect("Failed to parse JSON"); // Now we can print the Value since it implements Display println!("{}", res); }
Better Implementation: Type-Safe Parsing with Structs
Using serde_json::Value is flexible, but defining a struct that matches your JSON structure is far better—it gives you type safety, autocompletion, and avoids runtime errors from accessing non-existent fields. Here's how to do that:
First, ensure your Cargo.toml has the right dependencies:
[dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
Suppose your input.json looks like this:
{ "name": "Alice", "age": 30, "is_active": true }
Your Rust code would look like this:
use serde::Deserialize; use std::fs; // Derive Deserialize to let Serde parse JSON into this struct #[derive(Debug, Deserialize)] struct User { name: String, age: u32, is_active: bool, } fn main() { let path = "./src/input.json"; let data = fs::read_to_string(path).expect("Unable to read file"); // Parse directly into our User struct let user: User = serde_json::from_str(&data) .expect("Failed to parse JSON into User struct"); // Print using Debug format (or implement Display for custom, nicer output) println!("{:#?}", user); // Access individual fields safely with type checking println!("User name: {}", user.name); println!("User age: {}", user.age); }
Handling Errors Gracefully (Instead of expect)
For production code, it's better to avoid panicking with expect and handle errors explicitly. Here's how to use Rust's error handling system to return errors cleanly:
use serde::Deserialize; use std::fs; use std::error::Error; #[derive(Debug, Deserialize)] struct User { name: String, age: u32, is_active: bool, } fn main() -> Result<(), Box<dyn Error>> { let path = "./src/input.json"; let data = fs::read_to_string(path)?; let user: User = serde_json::from_str(&data)?; println!("{:#?}", user); Ok(()) }
This approach will propagate any error (file not found, invalid JSON, missing fields) and print a clear, actionable message without crashing abruptly.
内容的提问来源于stack exchange,提问作者turtle

