#json #serde-json #flattening #serde #unflattening #flatten-json

bin+lib json-unflattening

A Rust library for flattening and unflattening JSON structures

6 releases

0.1.5 Jan 8, 2025
0.1.4 Sep 18, 2024
0.1.3 Dec 14, 2023

#308 in Encoding

Download history 563/week @ 2024-10-18 367/week @ 2024-10-25 675/week @ 2024-11-01 438/week @ 2024-11-08 664/week @ 2024-11-15 821/week @ 2024-11-22 1338/week @ 2024-11-29 1214/week @ 2024-12-06 1174/week @ 2024-12-13 227/week @ 2024-12-20 313/week @ 2024-12-27 840/week @ 2025-01-03 1331/week @ 2025-01-10 1532/week @ 2025-01-17 1177/week @ 2025-01-24 778/week @ 2025-01-31

5,017 downloads per month
Used in 14 crates (via json-proof-token)

Apache-2.0

23KB
424 lines

json-unflattening

License

A Rust library for flattening and unflattening JSON structures. Uses serde_json for JSON serialization and deserialization.

Features

  • Flatten JSON: Convert nested JSON structures into a flattened form.
  • Unflatten JSON: Convert flattened JSON structures back to nested form.

Installation

Add this library to your Cargo.toml:

[dependencies]
json-unflattening = "0.1.4"

Usage

use json_unflattening::{flatten, unflatten};

fn main() {
    let input_json = json!({
        "name": {
            "first": "John",
            "last": "Doe"
        },
        "age": 30,
        "city": "New York",
        "hobbies": ["Reading", "Hiking", "Gaming"]
    });

    let flattened_json = flatten(&input_json).unwrap();
    println!("Flattened JSON: {:#}", serde_json::to_string_pretty(&flattened_json).unwrap());

    let unflattened_json = unflatten(&flattened_json).unwrap();
    println!("Unflattened JSON: {:#}", unflattened_json);
}

Example

Original JSON

{
  "name": {
      "first": "John",
      "last": "Doe"
  },
  "age": 30,
  "city": "New York",
  "hobbies": ["Reading", "Hiking", "Gaming"]
}

Flattened JSON

{
  "name.first": "John",
  "name.last": "Doe",
  "age": 30,
  "city": "New York",
  "hobbies[0]": "Reading",
  "hobbies[1]": "Hiking",
  "hobbies[2]": "Gaming"
}

Flattening process:

  1. Flatten Object Properties:

    • Flatten the "name" object properties using dot notation: "name.first" and "name.last".
    • Flatten the scalar properties "age" and "city" directly without modification.

    Result:

    {
      "name.first": "John",
      "name.last": "Doe",
      "age": 30,
      "city": "New York"
    }
    
  2. Flatten Array Elements:

    • Flatten the array "hobbies" by appending indices to each element: "hobbies[0]", "hobbies[1]", and "hobbies[2]".

    Result:

    {
      "name.first": "John",
      "name.last": "Doe",
      "age": 30,
      "city": "New York",
      "hobbies[0]": "Reading",
      "hobbies[1]": "Hiking",
      "hobbies[2]": "Gaming"
    }
    

Dependencies

~3.5–5.5MB
~101K SLoC