How to parse JSON in Rust
To parse json in Rust you need a library. The one used here is called rustc-serialize
.
The first step is to create a new project.
cargo new test_json
cd !$
And then include the dependency in the Cargo.toml file.
[package]
name = "test_json"
version = "0.1.0"
authors = ["Claus Witt <claus@wittnezz.dk>"]
[dependencies]
rustc-serialize = "0.3"
Next we will create a json file to parse.
{
"Person": {
"Name": "Claus Witt"
}
}
Finally we create a main.rs file.
extern crate rustc_serialize;
use rustc_serialize::json::Json;
use std::fs::File;
use std::io::Read;
fn main() {
let mut file = File::open("test.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json = Json::from_str(&data).unwrap();
println!("{}", json.find_path(&["Person", "Name"]).unwrap());
}
First we link our file with the dependency. Next we “use” the external library objects we need.
In the main method we open the file, and read its data into a string, and finallyy using Json::from_str parse the json. We use unwrap to tell the rust runtime that we want the value, or exit the program.
Last, but not least, we print the content of the path Person.Name