LoginSignup
4
2

Rust で JSON ファイルを読む

Last updated at Posted at 2020-07-13

フォルダー構造

$ tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── cities.json
├── src
│   └── main.rs
└── target
    └── debug
Cargo.toml
[package]
name = "json_read"
version = "0.1.0"
edition = "2018"

#

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
src/main.rs
// --------------------------------------------------------------------
/*
	json_read.rs

						Jul/15/2020
*/
// --------------------------------------------------------------------
use std::env;
use std::fs::File;
use std::io::BufReader;

// --------------------------------------------------------------------
fn main() -> std::io::Result<()> {
	eprintln!("*** 開始 ***");

	let args: Vec<_> = env::args().collect();
    
	let ref fname_in = args[1];

	let file = File::open(fname_in).unwrap();
	let reader = BufReader::new(file);

	let json: serde_json::Value = serde_json::from_reader(reader)?;

	let obj = json.as_object().unwrap();

	for (key,value) in obj.iter() {
		println!("{}\t{}\t{}\t{}",key,value["name"],
			value["population"],value["date_mod"]);
		}

	eprintln!("*** 終了 ***");

	Ok(())
}

// --------------------------------------------------------------------
cities.json
{
  "t0921": {
    "name": "宇都宮",
    "population": 41295,
    "date_mod": "2003-8-12"
  },
  "t0922": {
    "name": "小山",
    "population": 38756,
    "date_mod": "2003-5-15"
  },
  "t0923": {
    "name": "佐野",
    "population": 71294,
    "date_mod": "2003-6-8"
  },
  "t0924": {
    "name": "足利",
    "population": 27138,
    "date_mod": "2003-7-21"
  },
  "t0925": {
    "name": "日光",
    "population": 74682,
    "date_mod": "2003-4-19"
  },
  "t0926": {
    "name": "下野",
    "population": 82951,
    "date_mod": "2003-10-14"
  }
}

コンパイル

cargo build

実行

$ cargo run cities.json 
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target/debug/read cities.json`
*** 開始 ***
t0921	"宇都宮"	41295	"2003-8-12"
t0922	"小山"	38756	"2003-5-15"
t0923	"佐野"	71294	"2003-6-8"
t0924	"足利"	27138	"2003-7-21"
t0925	"日光"	74682	"2003-4-19"
t0926	"下野"	82951	"2003-10-14"
*** 終了 ***

確認したバージョン

$ rustc --version
rustc 1.75.0 (82e1608df 2023-12-21) (built from a source tarball)
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2