sort-keys 0.1.0

Recursively sort the keys of a JSON object, for deterministic output. A faithful port of the sort-keys npm package.
Documentation
  • Coverage
  • 100%
    9 out of 9 items documented3 out of 9 items with examples
  • Size
  • Source code size: 31.16 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 392.31 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 7s Average build duration of successful builds.
  • all releases: 7s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Homepage
  • trananhtung/sort-keys
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • trananhtung

sort-keys

All Contributors

crates.io docs.rs CI license

Recursively sort the keys of a JSON object — for deterministic, stable output.

A faithful Rust port of the widely-used sort-keys npm package, operating on [serde_json::Value].

  • Zero dependencies beyond serde_json
  • deep, ignore_keys, and a custom comparator
  • Differential-tested against the reference sort-keys implementation (60k cases)

Install

[dependencies]
sort-keys = "0.1"
serde_json = "1"

Usage

use serde_json::json;
use sort_keys::{sort_keys, sort_keys_with, sort_keys_by, Options};

assert_eq!(sort_keys(&json!({ "c": 0, "a": 0, "b": 0 })), json!({ "a": 0, "b": 0, "c": 0 }));

// Recurse into nested objects and arrays:
assert_eq!(
    sort_keys_with(&json!({ "b": { "d": 0, "c": 0 }, "a": 0 }), &Options::new().deep(true)),
    json!({ "a": 0, "b": { "c": 0, "d": 0 } })
);

// Custom comparator (reverse):
assert_eq!(
    sort_keys_by(&json!({ "a": 0, "b": 0 }), &Options::new(), |a, b| b.cmp(a)),
    json!({ "b": 0, "a": 0 })
);

// Keep some keys unsorted (they come first, in original order):
let _ = sort_keys_with(&json!({ "z": 0, "a": 0 }), &Options::new().ignore_keys(["z"]));

Notes

  • The default comparator orders keys by UTF-16 code units, matching JavaScript's default string sort. Use [sort_keys_by] for any other order.
  • This crate sorts all keys, including numeric-looking ones, by the comparator. (The JavaScript engine additionally reorders canonical integer keys first when serializing — a runtime quirk that does not apply to Rust; enable serde_json's preserve_order feature to keep this crate's sorted order on output.)

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.