append to a json file in rust

To append data to a JSON file in Rust, we can follow these steps:

  1. Open the file in append mode using the File::create() function.
  2. Deserialize the existing JSON data from the file.
  3. Append new data to the deserialized JSON.
  4. Serialize the updated JSON data in pretty format.
  5. Write the serialized JSON to the file.

Here's an example implementation:

main.rs
use serde::{Deserialize, Serialize};
use serde_json::{Result, Value};
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Write};

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

fn main() -> Result<()> {
    // Open the JSON file in append mode
    let file = OpenOptions::new()
        .write(true)
        .append(true)
        .create(true)
        .open("people.json")?;

    // If the file is empty, start with an empty JSON array
    let mut data: Vec<Person> = if file.metadata()?.len() == 0 {
        Vec::new()
    } else {
        let reader = BufReader::new(file);
        serde_json::from_reader(reader)?
    };

    // Add new data to the deserialized JSON
    data.push(Person {
        name: "Alice".into(),
        age: 27,
    });

    // Serialize in pretty format
    let serialized = serde_json::to_string_pretty(&data)?;

    // Write the serialized JSON to the file
    let mut writer = BufWriter::new(file);
    writeln!(writer, "{}", serialized)?;

    Ok(())
}
1030 chars
43 lines

In this example, we are creating a Person struct with a name and age field, and then appending a new Person object to the JSON file. We are using the serde and serde_json crates for serialization and deserialization, and the BufReader and BufWriter types to efficiently read and write to the file. Finally, we are formatting the JSON output with to_string_pretty() to make it more human-readable.

gistlibby LogSnag