Skip to main content

optional_json_from_sql

Function optional_json_from_sql 

Source
pub fn optional_json_from_sql<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<Value>, D::Error>
Expand description

Like json_from_sql for a NULL-able JSON column: NULL is None.

Use it as #[serde(default, deserialize_with = "ocre::optional_json_from_sql")] on an Option<serde_json::Value> field (default also accepts a missing key).

§Errors

Fails with the deserializer’s error when the text is not valid JSON; Db queries report it as Error::Internal.

§Examples

use serde::Deserialize;

#[derive(Deserialize)]
struct Post {
    #[serde(default, deserialize_with = "ocre::optional_json_from_sql")]
    metadata: Option<serde_json::Value>,
}

let post: Post = serde_json::from_str(r#"{"metadata": null}"#).unwrap();
assert_eq!(post.metadata, None);
let post: Post = serde_json::from_str(r#"{"metadata": "[1, 2]"}"#).unwrap();
assert_eq!(post.metadata, Some(serde_json::json!([1, 2])));