rustHow to write struct to json file in Rust
Writing a struct to a JSON file in Rust is a simple process. The following example code block shows how to do this:
use serde::{Serialize, Deserialize};
use serde_json::{Result, Value};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
fn main() -> Result<()> {
let p = Person {
name: String::from("John"),
age: 30,
phones: vec![String::from("+44 1234567"), String::from("+44 2345678")],
};
let j = serde_json::to_string(&p)?;
println!("{}", j);
let mut file = std::fs::File::create("person.json")?;
serde_json::to_writer_pretty(&mut file, &p)?;
Ok(())
}
The output of the example code is:
{
"name": "John",
"age": 30,
"phones": [
"+44 1234567",
"+44 2345678"
]
}
The code consists of the following parts:
use serde::{Serialize, Deserialize};
- imports theSerialize
andDeserialize
traits from theserde
crate.#[derive(Serialize, Deserialize)]
- derives theSerialize
andDeserialize
traits for thePerson
struct.let p = Person { ... }
- creates an instance of thePerson
struct.let j = serde_json::to_string(&p)?;
- serializes thePerson
struct to a JSON string.let mut file = std::fs::File::create("person.json")?;
- creates a file calledperson.json
.serde_json::to_writer_pretty(&mut file, &p)?;
- serializes thePerson
struct to theperson.json
file.
Helpful links
Related
- How to convert struct to bytes in Rust
- How to init zero struct in Rust
- How to update struct in Rust
- Example of struct private field in Rust
- Example of Rust struct with closure
- How to copy struct in Rust
- How to pretty print a struct in Rust
- How to convert struct to protobuf in Rust
- Example of struct of structs in Rust
More of Rust
- How to convert Rust bytes to a vector of u8?
- How to extend struct from another struct in Rust
- How to convert the keys of a Rust HashMap to a vector?
- How to clear a Rust HashMap?
- How do I drop a variable in Rust?
- How to get all elements of a Rust slice except the last one?
- What is an enum variable in Rust?
- How to compare with null in Rust
- How to escape dots with regex in Rust?
See more codes...