Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active January 27, 2016 01:49
Show Gist options
  • Save jorendorff/598db8988cc6972b3905 to your computer and use it in GitHub Desktop.
Save jorendorff/598db8988cc6972b3905 to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
#[derive(Debug)]
enum JSON {
Null,
Boolean(bool),
Number(f64),
String(String),
Array(Vec<JSON>),
Object(HashMap<String, JSON>)
}
trait CoerceIntoJSON {
fn into_json(self) -> JSON;
}
impl CoerceIntoJSON for JSON {
fn into_json(self) -> JSON {
self
}
}
impl CoerceIntoJSON for bool {
fn into_json(self) -> JSON {
JSON::Boolean(self)
}
}
impl CoerceIntoJSON for i32 {
fn into_json(self) -> JSON {
JSON::Number(self as f64)
}
}
impl CoerceIntoJSON for f64 {
fn into_json(self) -> JSON {
JSON::Number(self)
}
}
impl CoerceIntoJSON for &'static str {
fn into_json(self) -> JSON {
JSON::String(self.to_string())
}
}
macro_rules! as_expr {
($x:expr) => { $x }
}
macro_rules! json {
(null) => {
JSON::Null
};
({ $( $key:tt : $value:tt ),* }) => {
JSON::Object(vec![$( (as_expr!($key).to_string(), json!($value)) ),*].into_iter().collect())
};
([ $( $value:expr ),* ]) => {
JSON::Array(vec![])
};
($other:expr) => {
$other.into_json()
}
}
fn main() {
let some_rust_data = "something i got out of a config file";
let params = json!({
"nothing": null,
"two": 2,
"names": ["sonny", "bryan", "josh"],
"nested_object": {
"fruit": "banana",
"animal": "star-nosed mole",
"number": 2
},
"some-rust-data": (some_rust_data)
});
println!("{:?}", params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment