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 theSerializeandDeserializetraits from theserdecrate. -
#[derive(Serialize, Deserialize)]: This derives theSerializeandDeserializetraits for thePersonstruct. -
let json = serde_json::to_string(&map).unwrap();: This uses theserde_jsoncrate to serialize themapinto a JSON string. -
println!("{}", json);: This prints the JSON string to the console.
Helpful links
Related
- How to sort a Rust HashMap?
- How to use an enum in a Rust HashMap?
- How to declare a constant Rust HashMap?
- How to create a Rust HashMap with a string key?
- How to convert the keys of a Rust HashMap to a vector?
- How to remove an element from a Rust HashMap if a condition is met?
- How to create a HashMap of pointers in Rust?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to a struct?
More of Rust
- How to replace all matches using Rust regex?
- Regex example to match multiline string in Rust?
- How to use non-capturing groups in Rust regex?
- How to replace all using regex in Rust?
- How to use regex builder in Rust?
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- How to declare a constant Rust HashMap?
- How to get an entry from a HashSet in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
See more codes...