Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a vector to a json file?

Tags:

json

vector

rust

How to write a vector to a JSON file in rust?

Code:

use std::fs::File;
use std::io::prelude::*;

let vec1 = vec![1.0,2.0,2.1,0.6];

let mut file = File::create("results.json").unwrap();
let data = serde_json::to_string(&vec1).unwrap();

file.write(&data);

Error:

mismatched types
expected reference `&[u8]`
   found reference `&std::string::String`rustc(E0308)
like image 647
AlgoQ Avatar asked Oct 24 '25 11:10

AlgoQ


1 Answers

Instead of writing the data to an in-memory string first, you can also write it directly to the file:

use std::fs::File;
use std::io::{BufWriter, Write};

fn main() -> std::io::Result<()> {
    let vec = vec![1, 2, 3];
    let file = File::create("a")?;
    let mut writer = BufWriter::new(file);
    serde_json::to_writer(&mut writer, &vec)?;
    writer.flush()?;
    Ok(())
}

This approach has a lower memory footprint and is generally preferred. Note that you should use buffered writes to the file, since serialization could otherwise result in many small writes to the file, which would severely reduce performance.

If you need to write the data to memory first for some reason, I suggest using serde_json::to_vec() instead of serde_json::to_string(), since that function will give you a Vec<u8> immediately.

like image 193
Sven Marnach Avatar answered Oct 26 '25 04:10

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!