#serde-json #json #serde #character

serde-json-fmt

Configurable formatting for serde_json serialization

1 unstable release

0.1.0 Apr 15, 2023

#1293 in Encoding

Download history 36/week @ 2024-07-22 23/week @ 2024-07-29 188/week @ 2024-08-05 42/week @ 2024-08-12 20/week @ 2024-08-19 62/week @ 2024-08-26 62/week @ 2024-09-02 92/week @ 2024-09-09 90/week @ 2024-09-16 59/week @ 2024-09-23 58/week @ 2024-09-30 43/week @ 2024-10-07 24/week @ 2024-10-14 42/week @ 2024-10-21 1/week @ 2024-10-28 16/week @ 2024-11-04

83 downloads per month
Used in 2 crates

MIT license

44KB
901 lines

Project Status: Active – The project has reached a stable, usable state and is being actively developed. CI Status codecov.io MIT License

GitHub | crates.io | Documentation | Issues

The serde-json-fmt crate lets you create custom serde_json formatters with the indentation, separators, and ASCII requirements of your choice.

serde_json itself only directly provides the ability to produce JSON in either "compact" form or "pretty" form, with the only customizable aspect being the string used for pretty indentation. serde-json-fmt complements serde_json to let you also customize the whitespace around commas & colons and whether to escape non-ASCII characters.

Installation

serde-json-fmt requires version 1.60 of Rust or higher. To use the serde-json-fmt library in your Cargo project, add the following to your Cargo.toml:

[dependencies]
serde-json-fmt = "0.1.0"

Examples

Say you want to serialize a value in one-line "compact" form, but you want a space after each colon & comma, something that serde_json's compact form doesn't do. serde-json-fmt lets you do that:

use serde_json::json;
use serde_json_fmt::JsonFormat;

let value = json!({
    "colors": ["red", "blue", "taupe"],
    "sub": {
        "name": "Foo",
        "on": true,
        "size": 17
    }
});

let s = JsonFormat::new()
    .comma(", ")
    .unwrap()
    .colon(": ")
    .unwrap()
    .format_to_string(&value)
    .unwrap();

assert_eq!(
    s,
    r#"{"colors": ["red", "blue", "taupe"], "sub": {"name": "Foo", "on": true, "size": 17}}"#
);

Say you want to format a value in multiline "pretty" form, but using four-space indents and with all non-ASCII characters encoded as \uXXXX escape sequences. serde-json-fmt lets you do that:

use serde_json::json;
use serde_json_fmt::JsonFormat;

let value = json!({
    "emojis": {
        "goat":"🐐",
        "pineapple": "🍍",
        "smile": "😀",
    },
    "greek": {
        "α": "alpha",
        "β": "beta",
        "γ": "gamma",
    }
});

let s = JsonFormat::pretty()
    .indent_width(Some(4))
    .ascii(true)
    .format_to_string(&value)
    .unwrap();

assert_eq!(s, r#"{
    "emojis": {
        "goat": "\ud83d\udc10",
        "pineapple": "\ud83c\udf4d",
        "smile": "\ud83d\ude00"
    },
    "greek": {
        "\u03b1": "alpha",
        "\u03b2": "beta",
        "\u03b3": "gamma"
    }
}"#);

Dependencies

~0.6–1.1MB
~22K SLoC