Skip to content

Instantly share code, notes, and snippets.

@orthecreedence
Last active June 25, 2016 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orthecreedence/09f266ef01eb4b54ecd234644824e717 to your computer and use it in GitHub Desktop.
Save orthecreedence/09f266ef01eb4b54ecd234644824e717 to your computer and use it in GitHub Desktop.
Rust example
extern crate serde_json;
use self::serde_json::Value;
use self::serde_json::Value::{I64, U64, F64, Bool, Null, Object, Array};
fn grab(keys: Vec<&str>, data: Value) -> Result<Value, String> {
let last: bool = keys.len() == 0;
if last { return Ok(data); }
let key = keys[0];
match data {
I64(_) | U64(_) | F64(_) | serde_json::Value::String(_) | Bool(_) | Null => {
return Err(format!("not found"));
},
Object(_) => {
match data.as_object().and_then(|obj| obj.get(key)) {
Some(d) => grab(keys[1..].to_vec(), d.clone()),
None => Err(format!("not found")),
}
},
Array(_) => {
let key = match key.parse::<usize>() {
Ok(x) => x,
Err(e) => return Err(format!("problem parsing integer: {:?}", e)),
};
// TODO: fix dupe code here
match data.as_array().and_then(|obj| obj.get(key)) {
Some(d) => grab(keys[1..].to_vec(), d.clone()),
None => Err(format!("not found")),
}
},
}
}
fn test() {
let data: Value = match serde_json::from_str("[\"test\",{\"name\":\"slappy\"},2,3]") {
Ok(j) => j,
Err(e) => {
warn!("problem parsing JSON, {:?}", e);
return
}
};
match json::grab(vec!["1", "name"], data).unwrap() {
Value::I64(x) => println!("i64: {}", x),
Value::U64(x) => println!("u64: {}", x),
Value::F64(x) => println!("f64: {}", x),
Value::String(x) => println!("str: {}", x),
Value::Bool(x) => println!("bool: {}", x),
Value::Null => println!("Null"),
Value::Object(_) => println!("got object"),
Value::Array(_) => println!("got array"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment