toml-rs/examples/toml2json.rs

51 lines
1.4 KiB
Rust
Raw Normal View History

2015-06-08 01:12:57 -05:00
#![deny(warnings)]
extern crate serde_json;
2018-12-17 19:45:35 -06:00
extern crate toml;
2015-06-08 01:12:57 -05:00
use std::env;
2018-12-17 19:45:35 -06:00
use std::fs::File;
2015-06-08 01:12:57 -05:00
use std::io;
use std::io::prelude::*;
use serde_json::Value as Json;
2018-12-17 19:45:35 -06:00
use toml::Value as Toml;
2015-06-08 01:12:57 -05:00
fn main() {
let mut args = env::args();
let mut input = String::new();
if args.len() > 1 {
2015-06-08 01:12:57 -05:00
let name = args.nth(1).unwrap();
2018-12-17 19:45:35 -06:00
File::open(&name)
.and_then(|mut f| f.read_to_string(&mut input))
.unwrap();
2015-06-08 01:12:57 -05:00
} else {
io::stdin().read_to_string(&mut input).unwrap();
}
2015-06-08 01:12:57 -05:00
match input.parse() {
Ok(toml) => {
let json = convert(toml);
println!("{}", serde_json::to_string_pretty(&json).unwrap());
2015-06-08 01:12:57 -05:00
}
Err(error) => println!("failed to parse TOML: {}", error),
}
2015-06-08 01:12:57 -05:00
}
fn convert(toml: Toml) -> Json {
2015-06-08 01:12:57 -05:00
match toml {
Toml::String(s) => Json::String(s),
Toml::Integer(i) => Json::Number(i.into()),
Toml::Float(f) => {
2018-12-17 19:45:35 -06:00
let n = serde_json::Number::from_f64(f).expect("float infinite and nan not allowed");
Json::Number(n)
}
Toml::Boolean(b) => Json::Bool(b),
Toml::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()),
2018-12-17 19:45:35 -06:00
Toml::Table(table) => {
Json::Object(table.into_iter().map(|(k, v)| (k, convert(v))).collect())
}
Toml::Datetime(dt) => Json::String(dt.to_string()),
2015-06-08 01:12:57 -05:00
}
}