Skip to content

Instantly share code, notes, and snippets.

@dcormier
Last active November 4, 2025 22:02
Show Gist options
  • Select an option

  • Save dcormier/3f35e3e1d098becafd45ad82c111f448 to your computer and use it in GitHub Desktop.

Select an option

Save dcormier/3f35e3e1d098becafd45ad82c111f448 to your computer and use it in GitHub Desktop.
See the fields available in a JSON value without showing scalar values
use serde_json::Value;
/// Recursively maps the structure of a [`serde_json::Map`], replacing scalar values
/// with type indicators.
pub fn map_structure<'a, I>(item: I) -> Value
where
I: IntoIterator<Item = (&'a String, &'a Value)> + 'a,
{
Value::Object(
item.into_iter()
.map(|(k, v)| (k.to_owned(), value_structure(v)))
.collect(),
)
}
/// Recursively maps the structure of a [`serde_json::Value`], replacing scalar values
/// with type indicators.
pub fn value_structure(value: &Value) -> Value {
match value {
Value::Null => value.clone(),
Value::Bool(_) => "[bool]".into(),
Value::Number(_) => "[number]".into(),
Value::String(_) => "[string]".into(),
Value::Object(map) => map_structure(map),
Value::Array(array) => array_structure(array),
}
}
/// Recursively maps the structure of a [`serde_json::Value::Array`], replacing
/// scalar values with type indicators.
pub fn array_structure(array: &[Value]) -> Value {
Value::Array(array.iter().map(value_structure).collect())
}
#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
use serde_json::json;
use super::map_structure;
#[test]
fn test_key_structure() {
let input = json!({
"a": 1,
"b": true,
"c": null,
"d": "a string",
"e": [
1,
true,
null,
"a string",
[1, 2, 3],
{
"f": 1,
"g": true,
"h": null,
"i": "a string",
"j": [1, 2, 3],
"k": {
"l": 10,
},
},
],
});
let expected = json!({
"a": "[number]",
"b": "[bool]",
"c": null,
"d": "[string]",
"e": [
"[number]",
"[bool]",
null,
"[string]",
["[number]", "[number]", "[number]"],
{
"f": "[number]",
"g": "[bool]",
"h": null,
"i": "[string]",
"j": ["[number]", "[number]", "[number]"],
"k": {
"l": "[number]",
},
},
],
});
let result = map_structure(input.as_object().unwrap());
assert_eq!(result, expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment