#jsonb #json #diesel

diesel_json

Json wrapper type for JsonB data handling in diesel

5 unstable releases

0.3.0 Sep 27, 2025
0.2.1 Jul 5, 2023
0.2.0 Feb 4, 2023
0.1.1 Jan 18, 2021
0.1.0 Jan 17, 2021

#1232 in Database interfaces

Download history 2549/week @ 2025-10-26 1659/week @ 2025-11-02 1798/week @ 2025-11-09 1728/week @ 2025-11-16 1541/week @ 2025-11-23 1749/week @ 2025-11-30 2470/week @ 2025-12-07 1875/week @ 2025-12-14 1361/week @ 2025-12-21 1048/week @ 2025-12-28 2362/week @ 2026-01-04 3001/week @ 2026-01-11 2094/week @ 2026-01-18 2029/week @ 2026-01-25 2333/week @ 2026-02-01 2684/week @ 2026-02-08

9,232 downloads per month
Used in 2 crates (via warg-server)

MIT license

9KB
107 lines

diesel_json

Provides a wrapper diesel_json::Json type that can be directly used to wrap serde serializable, deserializable structures and recognize them as queryable, insertable JsonB fields.

Getting started

Add diesel_json dependency to Cargo.toml.

  • Diesel 2.0 supported:
    • diesel_json = "0.3" with diesel postgres_backend feature requirement.
    • diesel_json = "0.2" with diesel postgres feature requirement.
  • Diesel 1.4 supported: diesel_json = "0.1"

Wrap data structures into diesel_json::Json type.

#[derive(Serialize, Deserialize, Debug)]
struct ComplexStruct {
  // ...
}

use diesel_json::Json;

#[derive(Serialize, Deserialize, Queryable, Insertable, AsChangeset, Identifiable)]
struct ExampleTable {
    // ...
    // Field that will be stored in Jsonb format
    jsonb_field: diesel_json::Json<ComplexStruct>,
    // Or simply as 
    jsonb_field2: Json<ComplexStruct>,
    // ...
}

Json type provides new function for object initialization, implements Deref, DerefMut, AsRef, AsMut and other traits that maps data access directly to underlying data.

See tests/postgresql.rs for example use.

Why should I use this library?

Without wrapper type for each unique type you store as JsonB field you would need to use serde_json::Value directly or implement your own implementation for following traits:

impl<T> FromSql<sql_types::JsonB, Pg> for Json<T> {}
impl<T> ToSql<sql_types::JsonB, Pg> for Json<T> {}

TODO:

  • Support not only JsonB, but also Json postgres type
  • Support more database drivers
    • PostgreSQL
    • MySql
    • SQLite
  • Improve testing of the library
    • Test insertion and retrieval of nullable/non-nullable JsonB postgresql fields.
    • Add support and test Json field insertion and retrieval
    • TODO(Expand): Add support for other database driver Json fields

Dependencies

~4.5MB
~89K SLoC