JairusSW / as-json

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

Feature request: Add decorator to omit empty fields #70

Closed mattjohnsonpint closed 5 months ago

mattjohnsonpint commented 5 months ago

It would be useful for JSON.stringify to have some capability to omit empty fields.

Something like this:

@json
class Foo {
  @omitempty
  bar!: string;
}

Though it may be tricky to define "empty". If a field is type string | null (or SomeObject | null) then empty would imply nullable, not empty string:

@json
class Foo {
  @omitnull
  bar!: string | null;
}

Though, AssemblyScript doesn't allow primitives to be nullable (ie., i32 | null won't compile). So maybe there's also a need for another syntax, such as:

@json
class Foo {
  @omitwhen(0)
  bar!: i32;
}

Or maybe @omitwhen("") and @omitwhen(null) could work, then you'd only need one.

Your call, of course. 😄

JairusSW commented 5 months ago

I'll add a few ways to configure properly in the next major release

JairusSW commented 5 months ago

Including this

JairusSW commented 5 months ago

Okay, so what I'm doing would be used like so:

@json
class Foo {
  @omitnull
  optionalNumber: Box<i32> | null = null;
  @omitif("this.tristateValue!.unwrap() == false")
  tristateValue: Box<bool> | null = null;
}

const foo: Foo = {
  optionalNumber: null,
  tristateValue: Box.from(true)
}

console.log(JSON.stringify(foo));

const p1 = JSON.parse<Box<i32> | null>("null");
console.log(JSON.stringify<Box<i32> | null>(p1));
console.log(changetype<usize>(p1).toString())
const p2 = JSON.parse<Foo>("{\"optionalNumber\":null,\"tristateValue\":false}");
console.log(JSON.stringify(p2));

the user can insert their own conditions for it to be omitted

JairusSW commented 5 months ago

Its a bit unconventional, but it should work