Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple value possibilities #35

Open
iamisti opened this issue Jan 5, 2022 · 1 comment
Open

Multiple value possibilities #35

iamisti opened this issue Jan 5, 2022 · 1 comment

Comments

@iamisti
Copy link

iamisti commented Jan 5, 2022

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
Copy link

ZiuChen commented Jan 28, 2023

我也遇到了这个问题,在我的场景下,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 }
  ]
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants