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::Deserializegenerates an implementation ofserde::Deserializefor the struct. We recommend using a full-path form (serde_query::Deserialize) when deriving to disambiguate between serde and this crate.serde_query::DeserializeQuerygeneratesserde::DeserializeforQuery<T>wrapper. This derive macro is useful if you want twoDeserializeimplementation. For example, you may wantDeserializeQueryfor querying an API andDeserializefor 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:
.fieldsyntax: You can use the.fieldsyntax to extract a field from a struct. For example,.nameextracts thenamefield. If the field name contains special characters, you can use the.["field"]syntax to quote the field name. For example,.["first-name"]extracts thefirst-namefield. 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.[].nameextracts thenamefield from each element in thefriendsarray..[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 thefriendsarray.
Traits§
- Deserialize
Query - A data structure that can be deserialized with a query.
Type Aliases§
- Query
- Convenient type alias for the query type.
Derive Macros§
- Deserialize
- Derive macro that generates
serde::Deserializedirectly. - Deserialize
Query - Derive macro for
DeserializeQuerytrait.