Skip to main content

patch_json

Function patch_json 

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

Deserializes an optional JSON field of a partial update into keep / clear / set.

patch for Option<Option<serde_json::Value>> fields: a missing field is None, null is Some(None), any other JSON value (strings included, taken as JSON strings, not parsed) is Some(Some(value)). Use with #[serde(default, deserialize_with = "ocre::patch_json")].

§Errors

Only the deserializer’s own errors (malformed input); every JSON value is accepted.

§Examples

use serde::Deserialize;
use serde_json::json;

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

let parse = |json| serde_json::from_str::<PostChanges>(json).unwrap().metadata;
assert_eq!(parse("{}"), None);
assert_eq!(parse(r#"{"metadata": null}"#), Some(None));
assert_eq!(parse(r#"{"metadata": {"a": 1}}"#), Some(Some(json!({"a": 1}))));
assert_eq!(parse(r#"{"metadata": "{}"}"#), Some(Some(json!("{}"))));