Created
July 10, 2020 21:22
-
-
Save matthewharwood/6ad0f9d4a5d3d0526275ab115c5e7ab3 to your computer and use it in GitHub Desktop.
A implementation of deepkeys for rust
This file contains hidden or 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
use serde_json::{Value}; | |
fn deep_keys(value: &Value, current_path: Vec<String>, output: &mut Vec<Vec<String>>) { | |
if current_path.len() > 0 { | |
output.push(current_path.clone()); | |
} | |
match value { | |
Value::Object(map) => { | |
for (k, v) in map { | |
let mut new_path = current_path.clone(); | |
new_path.push(k.to_owned()); | |
deep_keys(v, new_path, output); | |
} | |
}, | |
Value::Array(array) => { | |
for (i, v) in array.iter().enumerate() { | |
let mut new_path = current_path.clone(); | |
new_path.push(i.to_string().to_owned()); | |
deep_keys(v, new_path, output); | |
} | |
}, | |
_ => () | |
} | |
} | |
fn main() { | |
let mut output = vec![vec![]]; | |
let current_path = vec![]; | |
let data = r#" | |
{ | |
"name": "John Doe", | |
"age": 43, | |
"phones": [ | |
"+44 1234567", | |
"+44 2345678" | |
] | |
}"#; | |
let value:Value = serde_json::from_str(&data).expect("error"); | |
deep_keys(&value, current_path, &mut output); | |
println!("{:?}", output) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment