map-obj 0.1.0

Recursively map over the keys and values of a JSON object with a closure. A faithful port of the map-obj npm package.
Documentation
  • Coverage
  • 100%
    10 out of 10 items documented1 out of 5 items with examples
  • Size
  • Source code size: 31.34 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 382.16 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 5s Average build duration of successful builds.
  • all releases: 5s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/map-obj
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

map-obj

All Contributors

crates.io docs.rs CI license

Map over the keys and values of a JSON object.

Transform the keys and/or values of a serde_json::Value object with a closure, optionally recursing into nested objects and arrays. A faithful Rust port of the widely-used map-obj npm package — the building block behind key transforms like camelcase-keys.

  • deep recursion (into nested objects and objects within arrays)
  • Skip entries, rename keys, transform values, or stop recursion per entry
  • __proto__ keys are dropped
  • Differential-tested against the reference map-obj implementation (60k cases)

Install

[dependencies]
map-obj = "0.1"
serde_json = "1"

Usage

use serde_json::json;
use map_obj::{map_obj, MapEntry};

// Rename keys:
let upper = map_obj(&json!({ "a": 1, "b": 2 }), false, |key, value| {
    MapEntry::keep(key.to_uppercase(), value.clone())
});
assert_eq!(upper, json!({ "A": 1, "B": 2 }));

// Recurse with `deep`, transform values, and drop some entries:
let result = map_obj(&json!({ "keep": { "n": 2 }, "drop": 9 }), true, |key, value| {
    if key == "drop" {
        MapEntry::Skip
    } else if let Some(n) = value.as_i64() {
        MapEntry::keep(key, json!(n * 10))
    } else {
        MapEntry::keep(key, value.clone())
    }
});
assert_eq!(result, json!({ "keep": { "n": 20 } }));

Use [MapEntry::keep_without_recursing] to keep an entry but not descend into its value.

Contributors ✨

This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.

Thanks goes to these wonderful people:

License

Licensed under either of MIT or Apache-2.0 at your option.