#json #deserialize-json #postgresql #sqlx #queries #wrapper #decode

sqlx-transparent-json-decode

Decode JSON from Postgres sqlx queries, without the Json<> wrapper type

8 stable releases

new 3.0.0 Jul 23, 2024
2.2.2 Apr 24, 2024
2.2.1 Mar 27, 2024
2.1.0 Nov 27, 2023
1.0.0 May 27, 2023

#398 in Encoding

Download history 13/week @ 2024-04-04 106/week @ 2024-04-18 67/week @ 2024-04-25 16/week @ 2024-05-02 7/week @ 2024-05-09 28/week @ 2024-05-16 21/week @ 2024-05-23 22/week @ 2024-05-30 8/week @ 2024-06-06 6/week @ 2024-06-13 11/week @ 2024-06-20 10/week @ 2024-06-27 5/week @ 2024-07-04 187/week @ 2024-07-11 350/week @ 2024-07-18

555 downloads per month
Used in 3 crates

MIT/Apache

18KB
299 lines

sqlx-transparent-json-decode

docs.rs docs Download

This crate is meant for use with sqlx and allows you to query JSON or JSONB fields from PostgreSQL without needing to wrap the types in a sqlx::types::Json<> wrapper type.

use serde::{Deserialize, Serialize};
use sqlx_transparent_json_decode::sqlx_json_decode;

#[derive(Serialize, Deserialize)]
pub struct SomeJsonField {
    // Whatever fields match the JSON structure
    pub name: String,
    pub some_param: Option<String>,
    pub count: i32,
}

sqlx_json_decode!(SomeJsonField);

#[derive(sqlx::FromRow)]
pub struct QueryResult {
    pub id: i32,
    pub name: String,
    pub params: SomeJsonField,
}

Normally, you would need to use Json<SomeJsonField> as the type for params in the above example. This crate allows you to use SomeJsonField directly.

let result = sqlx::query_as!(
    QueryResult,
    r##"SELECT id,
        name,
        params as "params: SomeJsonField"
      FROM some_table"##,
).fetch_one(&pool).await?;

This crate also provides BoxedRawValue, a wrapper around Box<serde_json::value::RawValue> which can be decoded directly. This is otherwise difficult to do using sqlx's query macros.

let result = sqlx::query!(
    r##"SELECT id, data as "data: BoxedRawValue" FROM table##"
).fetch_one(&pool).await?;

Dependencies

~12–22MB
~351K SLoC