JairusSW / as-json

The only JSON library you'll need for AssemblyScript. SIMD enabled
MIT License
72 stars 13 forks source link

Add support for flattening complex properties #46

Closed doxblek closed 3 months ago

doxblek commented 1 year ago

One feature that comparable libraries such as serde for Rust offer, is the ability to flatten inner objects. This would be a nice addition for as-json.

From usage perspective, this could look like this:

@json
class MyInnerClass {
    first: string;
    second: i32;
}

@json
class MyOuterClass {
    otherProperty: f64;
    @flatten
    inner: MyInnerClass;
}

Serializing an instance of MyOuterClass would result in JSON similar to this:

{
    "otherProperty": 3.14,
    "first: "Hello World",
    "second": 42
}

The ability to flatten subproperties also helps to mitigate the shortcoming of AssemblyScript, that there are no nullable primitives as of today.

With flattening support this could be achieved like the following:

@json
class NullableI32 {
    value: i32;
}

@json
class Foo {
    @flatten
    optionalInt: NullableI32 | null;
}

// ...

let nullJSON = `{"optionalInt": null}`; // Or `{}` with optionalInt being undefined
let valueJSON = `{"optionalInt": 42}`;

let nullFoo = JSON.parse<Foo>(nullJSON); // nullFoo.optionalInt == null
let valueFoo = JSON.parse<Foo>(valueJSON); // valueFoo.optionalInt != null && valueFoo.optionalInt.value == 42

Without flattening, it is impossible to not propagate the helper properties to the outside world.

JairusSW commented 1 year ago

That's a great idea, @doxblek! I will look into it soon

JairusSW commented 3 months ago

Hey, over a year late, but this is implemented now