lucagez / slow-json-stringify

The slowest stringifier in the known universe. Just kidding, it's the fastest (:
https://github.com/lucagez/slow-json-stringify
MIT License
468 stars 17 forks source link

Multiple value possibilities #35

Open iamisti opened 2 years ago

iamisti commented 2 years ago

How do you deal with a JSON that can have a property that has a type of object or null?

So basically: { something: MyObject || null }

how do you define the serializer?

ZiuChen commented 1 year ago

我也遇到了这个问题,在我的场景下,friends属性的值可能为undefinedcomplex arrayempty array,这三种情况需要在serializer执行不同的处理方式

我需要类似于friends: undefined | array的声明,然而我并没有找到很好的实现方案。但是我只能在代码中保证friends的值不为undefined,而是一个空数组,下面是我的解决方案:

[
  { "id": 1, "friends": [{ "id": 5 }] },
  { "id": 2, "friends": [] },
  { "id": 3, "friends": undefined }
]
const stringify = sjs({
  data: attr(
    'array',
    sjs({
      id: attr('number'),
      friends: attr('array', (d) => {
        // when friends is [], d is undefined
        if (!d) return ''
        // pass d to sjs and transfer it to plain string
        else return sjs({ id: attr('number') })(d)
      })
    })
  )
})

stringify({
  data: [
    { id: 1, friends: [] },
    { id: 2, friends: [{ id: 1 }] }
    // { id: 3, friends: undefined }
  ]
})