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:

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 the name field. If the field name contains special characters, you can use the .["field"] syntax to quote the field name. For example, .["first-name"] extracts the first-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 the name field from each element in the friends 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 the friends 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.