rustHow to get a value by key from JSON in Rust?
Getting a value by key from JSON in Rust is easy with the serde_json
crate.
Example code
extern crate serde_json;
fn main() {
let data = r#"
{
"name": "John Doe",
"age": 43
}
"#;
let v: serde_json::Value = serde_json::from_str(data).unwrap();
let name = v["name"].as_str().unwrap();
println!("Name: {}", name);
}
Output example
Name: John Doe
The code above:
- imports the
serde_json
crate (extern crate serde_json;
) - creates a JSON string (
let data = r#"{...}"#;
) - parses the JSON string into a
serde_json::Value
(let v: serde_json::Value = serde_json::from_str(data).unwrap();
) - gets the value of the
name
key (let name = v["name"].as_str().unwrap();
) - prints the value of the
name
key (println!("Name: {}", name);
)
Helpful links
Related
More of Rust
- How to match whitespace with a regex in Rust?
- How to get a range from a slice in Rust?
- How to remove an element from a Rust HashMap if a condition is met?
- Yield generator in Rust
- How do I write a variable to a file in Rust?
- How to use captures_iter with regex in Rust?
- How to drain a Rust HashMap?
- How to use an async generator in Rust?
- How to convert a Rust slice to a tuple?
- How do I print the address of a variable in Rust?
See more codes...