Last active
February 21, 2019 18:31
-
-
Save nwtnni/a769fa093c4118c9716957957dcee332 to your computer and use it in GitHub Desktop.
CodyCigar JSON Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate serde_json; | |
use serde_json::Value; | |
fn extract(json: &Value, path: String, extracted: &mut Vec<(String, String)>) { | |
match json { | |
| Value::String(s) => extracted.push((path, s.clone())), | |
| Value::Null => extracted.push((path, "null".to_string())), | |
| Value::Number(n) => extracted.push((path, n.to_string())), | |
| Value::Bool(b) => extracted.push((path, b.to_string())), | |
| Value::Object(m) => { | |
for (k, v) in m { | |
extract(v, format!("{}/{}", path, k), extracted); | |
} | |
} | |
| Value::Array(a) => { | |
for (i, v) in a.iter().enumerate() { | |
extract(v, format!("{}[{}]", path, i), extracted); | |
} | |
} | |
} | |
} | |
fn main() { | |
let test = json! { | |
{ | |
"foo": { | |
"bar": { | |
"alpha": "alphaval", | |
"beta": "betaval" | |
}, | |
"baz": { | |
"alpha": "alphaval", | |
"gamma": "gammaval" | |
} | |
} | |
} | |
}; | |
let mut extracted = Vec::new(); | |
let root = "".to_string(); | |
extract(&test, root, &mut extracted); | |
println!("{:?}", extracted); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment