Jolt 数组转换

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

Jolt Array transformation

问题

我的输入 JSON 如下:

{
  "primary": 5,
  "quality": 4,
  "design": 5
}

输出应该是:

{
  "Ratings": [
    {
      "Name": "primary",
      "Value": 5
    },
    {
      "Name": "quality",
      "Value": 4
    }
  ]
}

也就是说,我不希望将输入的所有字段都放在数组中。

有人能提供如何使用 Jolt 来实现这个需求吗?谢谢。

英文:

My input json is like

{
  "primary": 5,
  "quality": 4,
  "design": 5
}

and output should be

{
  "Ratings": [
    {
      "Name": "primary",
      "Value": 5
    },
    {
      "Name": "quality",
      "Value": 4
    }
  ]
}

i.e I dont want all fields from input to be in array.

Could any one suggest how to do that using jolt..
Thanks in advance..

答案1

得分: 1

以下是翻译的代码部分:

[
  {
    "operation": "shift",
    "spec": {
      "p*|q*": { // 键以 p 或 q 开头的属性
        "$": "Ratings[#2].Name", // 通过循环遍历属性生成的索引来数组方式遍历属性的两个级别(`:`和`{`)之后的树路径
        "@": "Ratings[#2].Value"
      }
    }
  }
]
[
  {
    "operation": "shift",
    "spec": {
      "p*|q*": { 
        "$": "Ratings[#2].Name", 
        "@": "Ratings[#2].Value",
        "@1,ip": "ip" // 从对象内部调用属性
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "Ratings": "MANY",
      "*": "ONE"
    }
  }
]
英文:

Jolt 数组转换You can use the following shift transformation spec

[
  {
    "operation": "shift",
    "spec": {
      "p*|q*": { // the attributes whose keys start with p or q
        "$": "Ratings[#2].Name", // array-wise loop through the generated indexes of the attributes after traversing two levels( `:` and `{` ) for the tree path 
        "@": "Ratings[#2].Value"
      }
    }
  }
]

where $ wildcard represents keys, and @ wildcard represents values respectively

the demo on the site http://jolt-demo.appspot.com/ is

Jolt 数组转换

Edit : For the new proposed case you might tweak the spec as below

[
  {
    "operation": "shift",
    "spec": {
      "p*|q*": { 
        "$": "Ratings[#2].Name", 
        "@": "Ratings[#2].Value",
        "@1,ip": "ip" // call attribute from the inside of the object
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "Ratings": "MANY",
      "*": "ONE"
    }
  }
]

in order to prevent getting redundant null components

huangapple
  • 本文由 发表于 2023年2月27日 19:17:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579775.html
匿名

发表评论

匿名网友

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

确定