Crate valq

Crate valq 

Source
Expand description

valq provides macros for querying semi-structured (“JSON-ish”) data with the JavaScript-like syntax.

The principal macro provided by this crate is query_value!. Read the query_value doc for detailed usage. There is also a Result-returning variant of query_value!, called query_value_result!.

§Example

use serde::Deserialize;
use serde_json::{json, Value};
use valq::{query_value, query_value_result};

let data = json!({
    "package": {
        "name": "valq",
        "authors": ["jiftechnify"],
        "keywords": ["macro", "query", "json"]
    },
    "dependencies": {
        "paste": {
            "version": "1.0.15"
        }
    },
    "dev-dependencies": {
        "serde": {
            "version": "1.0.228",
            "features": ["derive"]
        }
    }
});

// Simple query
assert_eq!(
    query_value!(data.package.name -> str).unwrap(),
    "valq"
);

// Combining dot-notations & bracket-notations
assert_eq!(
    query_value!(data.package.authors[0] -> str).unwrap(),
    "jiftechnify"
);

// Deserializing a JSON array into a Vec
// Make sure that you put the line: `use serde::Deserialize`!
assert_eq!(
    query_value!(data.package.keywords >> (Vec<String>)).unwrap(),
    ["macro", "query", "json"],
);

// Result-returning variant for useful error
let res: valq::Result<&str> = query_value_result!(data.package.readme -> str);
if let Err(valq::Error::ValueNotFoundAtPath(path)) = res {
    assert_eq!(path, ".package.readme");
} else {
    panic!("should be error");
}

// Unwrapping with default value
assert_eq!(
    query_value!(data.package.readme -> str ?? "README.md"),
    "README.md",
);

// "Dynamic" query with bracket-notation
let dep_name = "paste";
assert_eq!(
    query_value!(data.dependencies[dep_name].version -> str).unwrap(),
    "1.0.15",
);

// Put it all together!
assert_eq!(
    query_value!(data["dev-dependencies"].serde.features[0] >> String ?? "none".into()),
    "derive".to_string(),
);

Macros§

query_value
A macro for querying an inner value of a structured (“JSON-ish”) data.
query_value_result
A Result-returning variant of query_value!.
transpose_tuple
Transposes an arbitrary length of tuple of Options/Results into an Option/Result of a tuple.

Enums§

Error
An error type returned from Result-returning macros provided by valq crate.

Type Aliases§

Result