rustHow to convert a Rust HashMap to JSON?
Converting a Rust HashMap to JSON can be done using the serde
crate. serde
provides a Serialize
trait which can be used to serialize a Rust data structure into a JSON string.
Example code
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
fn main() {
let mut map = std::collections::HashMap::new();
map.insert("John", Person {
name: "John".to_string(),
age: 30,
});
map.insert("Alice", Person {
name: "Alice".to_string(),
age: 25,
});
let json = serde_json::to_string(&map).unwrap();
println!("{}", json);
}
Output example
{"John":{"name":"John","age":30},"Alice":{"name":"Alice","age":25}}
Code explanation
-
use serde::{Serialize, Deserialize};
: This imports theSerialize
andDeserialize
traits from theserde
crate. -
#[derive(Serialize, Deserialize)]
: This derives theSerialize
andDeserialize
traits for thePerson
struct. -
let json = serde_json::to_string(&map).unwrap();
: This uses theserde_json
crate to serialize themap
into a JSON string. -
println!("{}", json);
: This prints the JSON string to the console.
Helpful links
Related
- How to implement PartialEq for a Rust HashMap?
- How to create a new Rust HashMap with values?
- How to use a tuple as a key in a Rust HashMap?
- How to sort a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to use a custom hash function with a Rust HashMap?
- How to use a HashBrown with a Rust HashMap?
- How to get the length of a Rust HashMap?
- How to create a HashMap of pointers in Rust?
- How to create a HashMap of traits in Rust?
More of Rust
- How to use non-capturing groups in Rust regex?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to replace a capture group using Rust regex?
- How to use named capture groups in Rust regex?
- How to parse JSON string in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to create a HashSet from a String in Rust?
See more codes...