Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a JSON field with Diesel?

I have this models:

use diesel::sql_types::Json;

#[derive(Queryable)]
pub struct GMapsLocation {
    pub id: i32,
    pub place_id: String,
    pub data: Json,
}

and am trying to query that column like this:

    let results = gmaps_locations
        .select((id, place_id, data))
        .load::<GMapsLocation>(&connection)
        .expect("Erorr loading locations");

And that is not working, giving me the error:

18   |         .load::<GMapsLocation>(&connection)
     |          ^^^^ the trait `Queryable<diesel::sql_types::Json, _>` is not implemented for `diesel::sql_types::Json`

The documentation does not give any examples and this error does not tell me anything.

like image 235
Alper Avatar asked Oct 15 '25 07:10

Alper


1 Answers

OK. I figured it out.

Just like the input value from the documentation is a serde_json::Value, the return value from the query is also a serde_json::Value. That is also what you have to put in your Queryable struct.

I have no clue what diesel::sql_types::Json is for then but it should not go in there.

So the working code is:

#[derive(Queryable, Debug)]
pub struct GMapsLocation {
    pub id: i32,
    pub place_id: String,
    pub data: serde_json::Value,
}

let results = gmaps_locations
    .select((id, place_id, data))
    .load::<GMapsLocation>(&connection)
    .expect("Erorr loading locations");

like image 187
Alper Avatar answered Oct 18 '25 03:10

Alper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!