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
- Example of struct private field in Rust
- Example of Rust struct with closure
- Example of struct of structs in Rust
- How to get struct value in Rust
- Example of bit field in Rust struct
- Rust struct without fields
- How to init zero struct in Rust
- How to convert struct to bytes in Rust
- Example of struct with vector field in Rust
- How to compare structs in Rust
More of Rust
- How to use regex to match a double quote in Rust?
- How to get a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to parse JSON string in Rust?
- How to use regex to match a group in Rust?
- How to use regex with bytes in Rust?
- How to replace all using regex in Rust?
- Hashshet example in Rust
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
See more codes...