5 releases (breaking)

0.5.0 Dec 27, 2022
0.4.0 Mar 22, 2021
0.3.0 Nov 3, 2020
0.2.0 Aug 31, 2020
0.1.0 Aug 17, 2020

#632 in Encoding

Download history 126/week @ 2023-11-24 61/week @ 2023-12-01 75/week @ 2023-12-08 73/week @ 2023-12-15 53/week @ 2023-12-22 47/week @ 2023-12-29 129/week @ 2024-01-05 95/week @ 2024-01-12 98/week @ 2024-01-19 267/week @ 2024-01-26 113/week @ 2024-02-02 95/week @ 2024-02-09 117/week @ 2024-02-16 190/week @ 2024-02-23 70/week @ 2024-03-01 21/week @ 2024-03-08

411 downloads per month
Used in 7 crates (2 directly)

MIT license

20KB
336 lines

Canonical JSON library

Canonical JSON is a variant of JSON in which each value has a single, unambiguous serialized form. This provides meaningful and repeatable hashes of encoded data.

Canonical JSON can be parsed by regular JSON parsers. The most notable differences compared to usual JSON format (RFC 7159 or serde_json::to_string()) are:

  • Object keys must appear in lexiographical order and must not be repeated
  • No inter-token whitespace
  • Unicode characters and escaped characters are escaped

This library follows gibson's Canonical JSON spec.

Usage

Add this to your Cargo.toml:

[dependencies]
canonical_json = "0.5.0"

Examples

   use serde_json::json;
   use canonical_json::ser::to_string;

   fn main() {
     to_string(&json!(null)); // returns "null"

     to_string(&json!("we ❤ Rust")); // returns "we \u2764 Rust""

     to_string(&json!(10.0_f64.powf(21.0))); // returns "1e+21"

     to_string(&json!({
         "a": "a",
         "id": "1",
         "b": "b"
     })); // returns "{"a":"a","b":"b","id":"1"}"; (orders object keys)

     to_string(&json!(vec!["one", "two", "three"])); // returns "["one","two","three"]"
   }

Test suite

Run the projet test suite:

$ cargo test

Run @gibson042's Canonical JSON test suite:

$ git clone git@github.com:gibson042/canonicaljson-spec.git
$ cd canonicaljson-spec/
$ ./test.sh ../canonicaljson-rs/demo/target/debug/demo

Some known errors:

  • lone leading surrogate in hex escape
  • number out of range
  • Non-token input after 896 characters: "\u6} surrogate pair\u2014U+1D306

See also

License

Licensed under MIT

Dependencies

~2.8–4.5MB
~86K SLoC