create a json file in rust

To create a JSON file in Rust, you first need to serialize your data into JSON format. The easiest way to do this is by using a crate called serde_json. Here is an example of how to serialize a HashMap into a JSON string:

main.rs
use std::fs::File;
use std::io::Write;
use serde::{Serialize};

fn main() {
    let mut map = std::collections::HashMap::new();
    map.insert("name", "John");
    map.insert("age", "30");

    let json_str = serde_json::to_string(&map).unwrap();

    let mut file = File::create("example.json").unwrap();
    file.write_all(json_str.as_bytes()).unwrap();
}
358 chars
15 lines

In this example, we first create a HashMap and insert some values into it. We then use serde_json::to_string to serialize the HashMap into a JSON string. Finally, we create a new File, and write the JSON string to the file.

Note that we are using the unwrap() method to handle errors in this example. In production code, you should use proper error handling to avoid panics.

gistlibby LogSnag