Alper
Alper

Reputation: 3953

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.

Upvotes: 4

Views: 2740

Answers (1)

Alper
Alper

Reputation: 3953

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");

Upvotes: 4

Related Questions