diesel::pg::expression::dsl

Function json_object

Source
pub fn json_object<Arr: TextArrayOrNullableTextArray + MaybeNullableValue<Json>, text_array>(
    text_array: text_array,
) -> json_object<Arr, text_array>
where text_array: AsExpression<Arr>,
Available on crate feature postgres_backend only.
Expand description

Builds a JSON object out of a text array. The array must have an even number of members, in which case they are taken as alternating key/value pairs

ยงExample

let json = diesel::select(json_object::<Array<Text>,_>(vec!["hello","world"]))
                .get_result::<Value>(connection)?;
let expected:Value = serde_json::json!({"hello":"world"});
assert_eq!(expected,json);

let json = diesel::select(json_object::<Array<Text>,_>(vec!["hello","world","John","Doe"]))
                .get_result::<Value>(connection)?;
let expected:Value = serde_json::json!({"hello":"world","John":"Doe"});
assert_eq!(expected,json);

let json = diesel::select(json_object::<Array<Text>,_>(vec!["hello","world","John"]))
                .get_result::<Value>(connection);
assert!(json.is_err());

let empty:Vec<String> = Vec::new();
let json = diesel::select(json_object::<Array<Nullable<Text>>,_>(empty))
                .get_result::<Value>(connection);
assert!(json.is_err());