rustHow to parse JSON string in Rust?
Parsing JSON string in Rust can be done using the serde
crate. serde
is a powerful library for serializing and deserializing data structures.
Example code
extern crate serde;
extern crate serde_json;
use serde_json::{Result, Value};
fn main() {
// Some JSON input data as a &str. Maybe this comes from the user.
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into serde_json::Value.
let v: Value = serde_json::from_str(data)?;
// Access parts of the data by indexing with square brackets.
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
}
Output example
Please call John Doe at the number +44 1234567
Code explanation
-
extern crate serde;
andextern crate serde_json;
: These two lines are used to import theserde
andserde_json
crates. -
use serde_json::{Result, Value};
: This line imports theResult
andValue
types from theserde_json
crate. -
let data = r#" ... "#;
: This line creates a string literal containing the JSON data. -
let v: Value = serde_json::from_str(data)?;
: This line parses the JSON data into aValue
type. -
println!("Please call {} at the number {}", v["name"], v["phones"][0]);
: This line prints out the parsed data.
Helpful links
Related
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...