aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2015-06-07 23:12:57 -0700
committerAlex Crichton <alex@alexcrichton.com>2015-06-07 23:47:29 -0700
commite96e25bec74e9dccbf56275913894bda561a3154 (patch)
tree81658445bcbb185f60811e403085a5271dc15a7f
parent6580b77a203f360cf9f519e773b1d89de4d1336b (diff)
downloadmilf-rs-e96e25bec74e9dccbf56275913894bda561a3154.tar.gz
milf-rs-e96e25bec74e9dccbf56275913894bda561a3154.zip
Add a toml to json example
-rw-r--r--examples/toml2json.rs57
1 files changed, 57 insertions, 0 deletions
diff --git a/examples/toml2json.rs b/examples/toml2json.rs
new file mode 100644
index 0000000..0d40680
--- /dev/null
+++ b/examples/toml2json.rs
@@ -0,0 +1,57 @@
+#![deny(warnings)]
+
+extern crate toml;
+extern crate rustc_serialize;
+
+use std::fs::File;
+use std::env;
+use std::io;
+use std::io::prelude::*;
+
+use toml::Value;
+use rustc_serialize::json::Json;
+
+fn main() {
+ let mut args = env::args();
+ let mut input = String::new();
+ let filename = if args.len() > 1 {
+ let name = args.nth(1).unwrap();
+ File::open(&name).and_then(|mut f| {
+ f.read_to_string(&mut input)
+ }).unwrap();
+ name
+ } else {
+ io::stdin().read_to_string(&mut input).unwrap();
+ "<stdin>".to_string()
+ };
+
+ let mut parser = toml::Parser::new(&input);
+ let toml = match parser.parse() {
+ Some(toml) => toml,
+ None => {
+ for err in &parser.errors {
+ let (loline, locol) = parser.to_linecol(err.lo);
+ let (hiline, hicol) = parser.to_linecol(err.hi);
+ println!("{}:{}:{}-{}:{} error: {}",
+ filename, loline, locol, hiline, hicol, err.desc);
+ }
+ return
+ }
+ };
+ let json = convert(Value::Table(toml));
+ println!("{}", json.pretty());
+}
+
+fn convert(toml: Value) -> Json {
+ match toml {
+ Value::String(s) => Json::String(s),
+ Value::Integer(i) => Json::I64(i),
+ Value::Float(f) => Json::F64(f),
+ Value::Boolean(b) => Json::Boolean(b),
+ Value::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()),
+ Value::Table(table) => Json::Object(table.into_iter().map(|(k, v)| {
+ (k, convert(v))
+ }).collect()),
+ Value::Datetime(dt) => Json::String(dt),
+ }
+}