Rust JSON Parsing Program: Read, Parse, and Print Specific data
Rust Handling Errors with Result and Option: Exercise-7 with Solution
Write a Rust program that reads a JSON file, parses it, and prints specific data fields, handling parsing and I/O errors.
Sample Solution:
Rust Code:
use std::fs; // Import the fs module for file handling
use serde_json; // Import the serde_json crate for JSON parsing
use std::error::Error; // Import the Error trait for error handling
// Define a struct to represent the JSON data structure
#[derive(Debug, serde::Deserialize)] // Implement the Deserialize trait for the struct
struct Data {
field1: String,
field2: i32,
field3: f64,
}
fn main() -> Result<(), Box<dyn Error>> {
let file_path = "data.json"; // Specify the path of the JSON file
let json_data = r#"[
{"field1": "Item1", "field2": 100, "field3": 3.14},
{"field1": "Item2", "field2": 200, "field3": 10.25}
]"#; // JSON data to write to the file
// Create the JSON file with the specified data
fs::write(file_path, json_data)?;
// Attempt to read and parse the JSON file
let json_content = fs::read_to_string(file_path)?;
let parsed_data: Vec<Data> = serde_json::from_str(&json_content)?;
// Print specific data fields from the parsed JSON data
println!("Parsed JSON data:");
for entry in parsed_data {
println!("Field1: {}, Field2: {}, Field3: {}", entry.field1, entry.field2, entry.field3);
}
Ok(()) // Return Ok if the program completes successfully
}
Output:
Parsed JSON data: Field1: Item1, Field2: 100, Field3: 3.14 Field1: Item2, Field2: 200, Field3: 10.25
Explanation:
Here's a brief explanation of the above Rust code:
- The code begins by importing the necessary modules and crates:
- std::fs: for file handling operations.
- serde_json: for JSON parsing.
- std::error::Error: to handle errors.
- It defines a struct "Data" using the #[derive(serde::Deserialize)] attribute to automatically derive the "Deserialize" trait, which allows parsing JSON into instances of this struct. The struct "Data" has fields 'field1' of type "String", 'field2' of type "i32", and 'field3' of type "f64".
- The "main()" function returns a Result<(), Box<dyn Error>>, indicating an error.
- Inside "main()", a JSON file path 'file_path' and JSON data 'json_data' are specified.
- The JSON data is written to the file specified by file_path using fs::write().
- The file contents are then read and stored in "json_content".
- The JSON content is parsed into a vector of "Data" structs using serde_json::from_str().
- The parsed data is printed out, showing the values of 'field1', 'field2', and 'field3' for each entry in the JSON array.
- Finally, Ok(()) is returned to indicate successful execution .
Rust Code Editor:
Previous: Rust Date Parser: Handling user input and Parsing errors.
Next: Rust Function: Find maximum value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/error_handling/rust-handling-errors-with-result-and-option-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics