In Rust, you can use the serde
and serde_json
crates to read and parse JSON files.
First, you need to add both of these crates to your project's Cargo.toml
file:
main.rs85 chars4 lines
Then, you can read the contents of a JSON file and parse it into a Rust data structure like this:
main.rs520 chars23 lines
In this example, we define a Person
struct and use the serde_derive
crate to automatically generate the deserialization code for us. We then open the data.json
file and read its contents into a String
, which we then parse into a Person
using serde_json::from_str()
. Finally, we print out the name and age of the person that we parsed from the JSON file.
Note that this example assumes that the JSON file contains a single Person
object. If your JSON file contains an array of objects, you will need to parse it using serde_json::from_str::<Vec<Person>>(&data)
instead.
gistlibby LogSnag