如果不存在默认的 JSON 属性,可以使用 Jolt。

huangapple go评论135阅读模式
英文:

Default JSON property if not exists using Jolt

问题

我想要设置一个默认值,只有在 JSON 属性不存在时才生效。

例如,以下是我的 Jolt 规范:

[
  {
    "operation": "modify-default-beta",
    "spec": {
      "lastName": "[empty]"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "firstName": "firstName",
      "lastName": "lastName"
    }
  }
]

当输入为:

{
  "firstName": "John"
}

输出如下所示:

{
  "firstName" : "John",
  "lastName" : "[empty]"
}

另一方面,当输入为:

{
  "firstName": "John",
  "lastName": null
}

我期望输出与输入相同:

{
  "firstName": "John",
  "lastName": null
}

是否有一种方法只在属性不存在时设置默认值,而不考虑其值。谢谢。

英文:

I want to set a default value only if the JSON property not exists.

For example, below is my Jolt spec :

[
  {
    "operation": "modify-default-beta",
    "spec": {
      "lastName": "[empty]"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "firstName": "firstName",
      "lastName": "lastName"
    }
  }
]

When input is :

{
  "firstName": "John"
}

the output is as expected :

{
  "firstName" : "John",
  "lastName" : "[empty]"
}

On the other hand when input is :

{
  "firstName": "John",
  "lastName": null
}

I'm expecting the output is same as the input :

{
  "firstName": "John",
  "lastName": null
}

is there anyway to default only when property not exists regardless of it value. Thanks

答案1

得分: 2

首先,shift转换是不必要的。您可以在修改转换中使用isNull函数,例如:

[
  {
    "operation": "modify-default-beta",
    "spec": {
      "lastName": ["=isNull(@(1,&))", "[empty]"]
    }
  }
]

其中:

  • @(1,&) 表示当前属性的值,例如 "lastName"ampersand代表 lastName 文字)
  • 如果函数能够运行,则直接返回值 null
    否则返回第二个参数 "[empty]"
英文:

First of all the shift transformation is not needed. You can use an isNull function within a modify transformation such as

[
  {
    "operation": "modify-default-beta",
    "spec": {
      "lastName": ["=isNull(@(1,&))", "[empty]"]
    }
  }
]

where

  • @(1,&) represents the value of the current attribute, eg.
    "lastName"(the ampersand stnds for the lastName literal)
  • if the function is able to run, then the value null returns directly,
    otherwise the second argument "[empty]" returns

huangapple
  • 本文由 发表于 2023年8月9日 10:16:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定