]> git.lizzy.rs Git - rust.git/commit
auto merge of #12780 : zslayton/rust/json-nav, r=alexcrichton
authorbors <bors@rust-lang.org>
Tue, 11 Mar 2014 18:17:01 +0000 (11:17 -0700)
committerbors <bors@rust-lang.org>
Tue, 11 Mar 2014 18:17:01 +0000 (11:17 -0700)
commit3bede9fd310540a0fd72371008f8aa606b23b11b
tree85cdfdcedcae25fafb202474b104b3163d572582
parent9f3ebd8fc50682d6e4ef549cb31e70171acdcd71
parent9e0cfa23e8b3d2d17302eefd9d728e63e7c6c108
auto merge of #12780 : zslayton/rust/json-nav, r=alexcrichton

This is my first non-docs contribution to Rust, so please let me know what I can fix. I probably should've submitted this to the mailing list first for comments, but it didn't take too long to implement so I figured I'd just give it a shot.

These changes are modeled loosely on the [JsonNode API](http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/JsonNode.html) provided by the [Jackson JSON processor](http://jackson.codehaus.org/).

Many common use cases for parsing JSON involve pulling one or more fields out of an object, however deeply nested. At present, this requires writing a pyramid of match statements. The added methods in this PR aim to make this a more painless process.

**Edited to reflect final implementation**

Example JSON:
```json
{
    "successful" : true,
    "status" : 200,
    "error" : null,
    "content" : {
        "vehicles" : [
            {"make" : "Toyota", "model" : "Camry", "year" : 1997},
            {"make" : "Honda", "model" : "Accord", "year" : 2003}
        ]
    }
}
```

Accessing "successful":
```rust
 let example_json : Json = from_str("...above json...").unwrap();
 let was_successful: Option<bool> = example_json.find(&~"successful").and_then(|j| j.as_boolean());
```

Accessing "status":
```rust
 let example_json : Json = from_str("...above json...").unwrap();
 let status_code : Option<f64> = example_json.find(&~"status").and_then(|j| j.as_number());
```

Accessing "vehicles":
```rust
 let example_json : Json = from_str("...above json...").unwrap();
 let vehicle_list: Option<List> = example_json.search(&~"vehicles").and_then(|j| j.as_list());
```

Accessing "vehicles" with an explicit path:
```rust
 let example_json : Json = from_str("...above json...").unwrap();
 let vehicle_list: Option<List> = example_json.find_path(&[&~"content", &~"vehicles"]).and_then(|j| j.as_list());
```

Accessing "error", which might be null or a string:
```rust
 let example_json : Json = from_str("...above json...").unwrap();
 let error: Option<Json> = example_json.find(&~"error");
 if error.is_null() { // This would be nicer as a match, I'm just illustrating the boolean test methods
    println!("Error is null, everything's fine.");
 } else if error.is_str(){
    println!("Something went wrong: {}", error.as_string().unwrap());
}
```

Some notes:
* Macros would help to eliminate some of the repetitiveness of the implementation, but I couldn't use them due to #4621. (**Edit**: There is no longer repetitive impl. Methods were simplified to make them more composable.)
* Would it be better to name methods after the Json enum type (e.g. `get_string`) or the associated Rust built-in? (e.g. `get_str`)
* TreeMap requires its keys to be &~str. Because of this, all of the new methods required &~str for their parameters. I'm uncertain what the best approach to fixing this is: neither demanding an owned pointer nor allocating within the methods to appease TreeMap's find() seems desirable. If I were able to take &str, people could put together paths easily with `"foo.bar.baz".split('.').collect();` (**Edit**: Follow on investigation into making TreeMap able to search by Equiv would be worthwhile.)
* At the moment, the `find_<sometype>` methods all find the first match for the provided key and attempt to return that value if it's of the specified type. This makes sense to me, but it's possible that users would interpret a call to `find_boolean("successful")` as looking for the first "successful" item that was a boolean rather than looking for the first "successful" and returning None if it isn't boolean. (**Edit**: No longer relevant.)

I hope this is helpful. Any feedback is appreciated!