Crate serde_query
source ·Expand description
A query language for Serde data model.
This crate provides serde_query::Deserialize
and serde_query::DeserializeQuery
derive
macros that generate serde::Deserialize
implementations with queries.
Example
use serde_query::Deserialize;
#[derive(Deserialize)]
struct Data {
#[query(".commits.[].author")]
authors: Vec<String>,
#[query(".count")]
count: usize,
}
let document = serde_json::json!({
"commits": [
{
"author": "Kou",
"hash": 0x0202,
},
{
"author": "Kasumi",
"hash": 0x1013,
},
{
"author": "Masaru",
"hash": 0x0809,
},
],
"count": 3,
}).to_string();
let data: Data = serde_json::from_str(&document)?;
assert_eq!(data.authors, vec!["Kou", "Kasumi", "Masaru"]);
assert_eq!(data.count, 3);
Derive macros
This crate provides the following derive macros for declaring queries:
serde_query::Deserialize
generates an implementation ofserde::Deserialize
for the struct. We recommend using a full-path form (serde_query::Deserialize
) when deriving to disambiguate between serde and this crate.serde_query::DeserializeQuery
generatesserde::Deserialize
forQuery<T>
wrapper. This derive macro is useful if you want twoDeserialize
implementation. For example, you may wantDeserializeQuery
for querying an API andDeserialize
for loading from file.
Using the #[query("...")]
annotation
serde-query let you write a jq-like query inside the #[query("...")]
annotation.
Note that every field must have a query annotation.
The supported syntaxes are as follows:
.field
syntax: You can use the.field
syntax to extract a field from a struct. For example,.name
extracts thename
field. If the field name contains special characters, you can use the.["field"]
syntax to quote the field name. For example,.["first-name"]
extracts thefirst-name
field. When quoting a field name, try using a raw string literal (i.e.,#[query(r#"..."#)]
)..[]
syntax: You can use the.[]
syntax to run the rest of the query for each element in an array and collect the results. For example,.friends.[].name
extracts thename
field from each element in thefriends
array..[n]
syntax: You can use the.[n]
syntax to extract the nth element from an array. For example,.friends.[0]
extracts the first element of thefriends
array.
Traits
A data structure that can be deserialized with a query.
Type Definitions
Convenient type alias for the query type.
Derive Macros
Derive macro that generates
serde::Deserialize
directly.Derive macro for
DeserializeQuery
trait.