read a json file in rust

In Rust, you can use the serde and serde_json crates to read and parse JSON files.

First, you need to add both of these crates to your project's Cargo.toml file:

main.rs
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
85 chars
4 lines

Then, you can read the contents of a JSON file and parse it into a Rust data structure like this:

main.rs
extern crate serde;
extern crate serde_json;

use std::fs::File;
use std::io::Read;

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let mut file = File::open("data.json").expect("failed to open file");
    let mut data = String::new();
    file.read_to_string(&mut data).expect("failed to read data");

    let person: Person = serde_json::from_str(&data).expect("failed to parse JSON");

    println!("Name: {}", person.name);
    println!("Age: {}", person.age);
}
520 chars
23 lines

In this example, we define a Person struct and use the serde_derive crate to automatically generate the deserialization code for us. We then open the data.json file and read its contents into a String, which we then parse into a Person using serde_json::from_str(). Finally, we print out the name and age of the person that we parsed from the JSON file.

Note that this example assumes that the JSON file contains a single Person object. If your JSON file contains an array of objects, you will need to parse it using serde_json::from_str::<Vec<Person>>(&data) instead.

gistlibby LogSnag