#json-object #json #json-key #serde-json #object #flatten #serde

flatten-json-object

Tiny Rust library for flattening JSON objects

9 releases (5 breaking)

0.6.1 Apr 16, 2022
0.6.0 Apr 15, 2022
0.5.0 Apr 13, 2022
0.4.0 Apr 12, 2022
0.1.2 Apr 5, 2022

#1773 in Encoding

Download history 926/week @ 2024-03-14 1292/week @ 2024-03-21 727/week @ 2024-03-28 980/week @ 2024-04-04 750/week @ 2024-04-11 807/week @ 2024-04-18 930/week @ 2024-04-25 1095/week @ 2024-05-02 661/week @ 2024-05-09 1063/week @ 2024-05-16 669/week @ 2024-05-23 873/week @ 2024-05-30 792/week @ 2024-06-06 995/week @ 2024-06-13 806/week @ 2024-06-20 1105/week @ 2024-06-27

3,840 downloads per month
Used in 3 crates

MIT license

23KB
395 lines

licence crates.io docs.rs ci

Robust Rust library for flattening JSON objects

Given a JSON object it produces another one with all the nested objects and arrays flattened. The string used to separate the concatenated keys, and the way the arrays are formatted can be configured.

Notes

  • Empty arrays and objects are ignored by default, but it's configurable.
  • The empty key "" and the JSON null value can be used without problems and are preserved.
  • Having two or more keys that end being the same after flattening the object returns an error.
  • The JSON value passed to be flattened must be an object. The object can contain any valid JSON, though.

Usage

In your Cargo.toml

[dependencies]
flatten-json-object = "0.6.1"

Example

use flatten_json_object::ArrayFormatting;
use flatten_json_object::Flattener;
use serde_json::json;

let obj = json!({
    "a": {
        "b": [1, 2.0, "c", null, true, {}, []],
        "" : "my_key_is_empty"
    },
    "" : "my_key_is_also_empty"
});
assert_eq!(
    Flattener::new()
        .set_key_separator(".")
        .set_array_formatting(ArrayFormatting::Surrounded {
            start: "[".to_string(),
            end: "]".to_string()
        })
        .set_preserve_empty_arrays(false)
        .set_preserve_empty_objects(false)
        .flatten(&obj)?,
    json!({
        "a.b[0]": 1,
        "a.b[1]": 2.0,
        "a.b[2]": "c",
        "a.b[3]": null,
        "a.b[4]": true,
        "a.": "my_key_is_empty",
        "": "my_key_is_also_empty",
    })
);

A trivial example that reads JSON from stdin and outputs the converted flat JSON to stdout can be found in examples/from_stdin.rs. To run it execute cargo run --example from_stdin.

Dependencies

~0.6–1.4MB
~32K SLoC