pub fn json_from_sql<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Value, D::Error>Expand description
Deserializes a JSON column (the JSON text D1 returns) into serde_json::Value.
Use it as #[serde(deserialize_with = "ocre::json_from_sql")] on a
serde_json::Value field. A string is parsed as JSON text; a value that is
not a string (e.g. a row cached as JSON) is taken as is.
§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(deserialize_with = "ocre::json_from_sql")]
metadata: serde_json::Value,
}
// As D1 returns it: JSON text in a TEXT column.
let post: Post = serde_json::from_str(r#"{"metadata": "{\"tags\":[\"rust\"]}"}"#).unwrap();
assert_eq!(post.metadata["tags"][0], "rust");
// Already parsed (a cached row): kept as is.
let post: Post = serde_json::from_str(r#"{"metadata": {"tags": []}}"#).unwrap();
assert_eq!(post.metadata, serde_json::json!({"tags": []}));