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 of structs in Rust
- Example of struct private field in Rust
- How to init zero struct in Rust
- How to serialize struct to xml in Rust
- Example of Rust struct with closure
- How to get struct value in Rust
- Example of bit field in Rust struct
- Rust struct without fields
- How to update struct in Rust
- How to convert struct to protobuf in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How do I create an array of strings in Rust?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to use regex captures in Rust?
- How to convert JSON to a struct in Rust?
- How to pop an element from a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...