Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a JSON File?

Tags:

json

rust

I have this so far in my goal to Parse this JSON data in Rust:

extern crate rustc_serialize; use rustc_serialize::json::Json; use std::fs::File; use std::io::copy; use std::io::stdout;  fn main() {     let mut file = File::open("text.json").unwrap();     let mut stdout = stdout();     let mut str = &copy(&mut file, &mut stdout).unwrap().to_string();     let data = Json::from_str(str).unwrap(); } 

and text.json is

{     "FirstName": "John",     "LastName": "Doe",     "Age": 43,     "Address": {         "Street": "Downing Street 10",         "City": "London",         "Country": "Great Britain"     },     "PhoneNumbers": [         "+44 1234567",         "+44 2345678"     ] } 

What should be my next step into parsing it? My primary goal is to get JSON data like this, and parse a key from it, like Age.

like image 375
Vikaton Avatar asked May 17 '15 22:05

Vikaton


People also ask

Is JSON easy to parse?

JSON is a data interchange format that is easy to parse and generate. JSON is an extension of the syntax used to describe object data in JavaScript. Yet, it's not restricted to use with JavaScript. It has a text format that uses object and array structures for the portable representation of data.

How do you parse a .JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.

What does it mean to parse a JSON file?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.

How do I convert a JSON file to readable?

If you need to convert a file containing Json text to a readable format, you need to convert that to an Object and implement toString() method(assuming converting to Java object) to print or write to another file in a much readabe format. You can use any Json API for this, for example Jackson JSON API.


2 Answers

Serde is the preferred JSON serialization provider. You can read the JSON text from a file a number of ways. Once you have it as a string, use serde_json::from_str:

fn main() {     let the_file = r#"{         "FirstName": "John",         "LastName": "Doe",         "Age": 43,         "Address": {             "Street": "Downing Street 10",             "City": "London",             "Country": "Great Britain"         },         "PhoneNumbers": [             "+44 1234567",             "+44 2345678"         ]     }"#;      let json: serde_json::Value =         serde_json::from_str(the_file).expect("JSON was not well-formatted"); } 

Cargo.toml:

[dependencies] serde = { version = "1.0.104", features = ["derive"] } serde_json = "1.0.48" 

You could even use something like serde_json::from_reader to read directly from an opened File.

Serde can be used for formats other than JSON and it can serialize and deserialize to a custom struct instead of an arbitrary collection:

use serde::Deserialize;  #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] struct Person {     first_name: String,     last_name: String,     age: u8,     address: Address,     phone_numbers: Vec<String>, }  #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] struct Address {     street: String,     city: String,     country: String, }  fn main() {     let the_file = /* ... */;      let person: Person = serde_json::from_str(the_file).expect("JSON was not well-formatted");     println!("{:?}", person) } 

Check the Serde website for more details.

like image 102
Shepmaster Avatar answered Oct 28 '22 16:10

Shepmaster


Solved by the many helpful members of the Rust community:

extern crate rustc_serialize; use rustc_serialize::json::Json; use std::fs::File; use std::io::Read;  fn main() {     let mut file = File::open("text.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(&["Address", "Street"]).unwrap()); } 
like image 42
Vikaton Avatar answered Oct 28 '22 14:10

Vikaton