1 unstable release

Uses old Rust 2015

0.0.1 Apr 11, 2015

#33 in #json-query


Used in mbutiles

BSD-2-Clause

31KB
772 lines

rust-jlens

Simple JSON query DSL for Rust


lib.rs:

Extract data from JSON

This crate provides a simple domain-specific language based on method chaining to construct and run queries against serialize::json::Json objects.

An object implementing the Selector trait describes how to select a set of nodes starting at a given path in a JSON document. The most basic selector can be created with the node() function: this selector always selects precisely the path given to it. All selectors have methods such as child() and key() which return a new selector. The new selector will select nodes relative to the output of the original according to some criteria. For example, node().child() selects all children of the initial node, while node().child().child() selects all children of the children of the initial node, and so on. By continuing to chain method calls in this manner, a selector object representing a complex query expression can be built up. Example:

// Test JSON document
let json = r#"
[
   {
       "foo": ["Hello, world!", 3.14, false]
   },
   {
       "foo": [42, true]
   },
   {
       "foo": "Nope"
   },
   {
       "bar": [42, "Hello, world!"]
   }
]"#.parse::<Json>().unwrap();

// Given a list, match all objects in it that
// have a "foo" key where the value is a list
// that contains either the string "Hello, world!"
// or the u64 42
let matches = json.query(
    list().child().wherein(
        key("foo").list().child().or(
            string().equals("Hello, world!"),
            uint64().equals(42))));

// Expected matches
let match1 = r#"{"foo": ["Hello, world!", 3.14, false]}"#.parse::<Json>().unwrap();
let match2 = r#"{"foo": [42, true]}"#.parse::<Json>().unwrap();

assert_eq!(matches.len(), 2);
assert!(matches.contains(& &match1));
assert!(matches.contains(& &match2));

The JsonExt trait provides a convenience method on Json objects which runs a selector and returns a Vec<&Json> of results.

Dependencies

~225KB