//! Canonical JSON: object keys sorted by their UTF-8 bytes at every depth, no //! whitespace, serde_json's number and string forms. The workspace builds //! serde_json with `preserve_order`, so a map keeps insertion order and the //! sort has to be done here rather than assumed. use serde_json::{Map, Value}; /// The canonical text of a value. pub fn canonical_json(value: &Value) -> String { serde_json::to_string(&sorted(value)).unwrap_or_default() } fn sorted(value: &Value) -> Value { match value { Value::Object(map) => { let mut keys: Vec<&String> = map.keys().collect(); keys.sort(); let mut out = Map::with_capacity(map.len()); for key in keys { out.insert(key.clone(), sorted(&map[key])); } Value::Object(out) } Value::Array(items) => Value::Array(items.iter().map(sorted).collect()), other => other.clone(), } }