#serde-json #canonical #json #serde

serde_canonical_json

Implements a CanonicalFormatter for serde_json

1 stable release

1.0.0 Mar 7, 2023

#1195 in Encoding

Download history 1195/week @ 2024-01-15 2/week @ 2024-02-19 12/week @ 2024-02-26 1/week @ 2024-03-11 1/week @ 2024-03-18 20/week @ 2024-04-01 2/week @ 2024-04-08 34/week @ 2024-04-15

57 downloads per month

MIT license

26KB
710 lines

serde_canonical_json

This crate provides a Canonical JSON formatter for serde_json.

Usage

use serde::Serialize;
use serde_json::Serializer;
use serde_canonical_json::CanonicalFormatter;


#[derive(Serialize)]
struct Data
{
    c: isize,
    b: bool,
    a: String,
}


fn main()
{
    let data = Data { c: 120, b: false, a: "Hello!".to_owned() };

    let mut ser = Serializer::with_formatter(Vec::new(), CanonicalFormatter::new());

    data.serialize(&mut ser).expect("Failed to serialize");
    
    let json = String::from_utf8(ser.into_inner()).expect("Failed to convert buffer to string");

    assert_eq!(json, r#"{"a":"Hello!","b":false,"c":120}"#);
}

lib.rs:

serde_canonical_json

This crate provides a Canonical JSON formatter for serde_json.

Usage

use serde::Serialize;
use serde_json::Serializer;
use serde_canonical_json::CanonicalFormatter;

// CanonicalFormatter will ensure our keys are in lexical order
#[derive(Serialize)]
struct Data
{
    c: isize,
    b: bool,
    a: String,
}

let data = Data { c: 120, b: false, a: "Hello!".to_owned() };

let mut ser = Serializer::with_formatter(Vec::new(), CanonicalFormatter::new());

data.serialize(&mut ser).unwrap();

let json = String::from_utf8(ser.into_inner()).unwrap();

assert_eq!(json, r#"{"a":"Hello!","b":false,"c":120}"#);

Dependencies

~2.5–4MB
~70K SLoC