[−][src]Crate serde_query
A query language for Serde data model.
This crate provides serde_query::Deserialize
derive macro that generates
serde::Deserialize
implementation with queries.
Example
#[derive(serde_query::Deserialize)] struct Data { #[query(".commit.authors.[0]")] first_author: String, #[query(".hash")] hash_value: u64, } let document = serde_json::to_string(&serde_json::json!({ "commit": { "authors": ["Kou", "Kasumi", "Masaru"], "date": "2020-09-10", }, "hash": 0xabcd, }))?; // The query is compatible with arbitrary data formats with serde support. let data: Data = serde_json::from_str(&document)?; assert_eq!(data.first_author, "Kou"); assert_eq!(data.hash_value, 0xabcd);
Derive macros
This crate provides the following two derive macros for declaring a query:
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.
Each field must have a #[query(...)]
attribute for specifying
which part of the document should be retrieved, starting from the root.
#[query(...)]
syntax
serde-query
currently supports the following syntax for stepping one level inside the document.
You can combine them to go further.
.field
for accessing a field with a namefield
of an object. The field name must be an alphabet followed by zero or more alphanumeric characters..["field"]
if the field name contains special characters. We recommend using a raw string literal for the query parameter (#[query(r#"..."#)]
)..[index]
for accessing an array element at positionindex
.
Note that mixing field access and index access at the same position of a document is a compile error.
Traits
DeserializeQuery | A data structure that can be deserialized with a query. |
Type Definitions
Query | Convenient type alias for the query type. |
Derive Macros
Deserialize | Derive macro that generates |
DeserializeQuery | Derive macro for |