JOLT转换以沿数组复制单个值

时间:2018-05-18 14:10:41

标签: json jolt

我想将JSON转换为键值对,同时将特定的单个值(即“timestamp”)复制到所有这些对。

输入JSON:

{
  "Timestamp": "2018-05-13T14:57:09",
  "first_key": "1023",
  "another_key": "1987",
  "yet_another_key": "677"
}

预期产出:

[ {
    "Timestamp": "2018-05-13T14:57:09.087",
    "key": "first_key",
    "value": "1023"
  },
  {
    "Timestamp": "2018-05-13T14:57:09.087",
    "key": "another_key",
    "value": "1987"
  },
  {
    "Timestamp": "2018-05-13T14:57:09.087",
    "key": "yet_another_key",
    "value": "677"
  }]

到目前为止我想出的是以下JOLT规范。它已经为所有不是“Timestamp”的条目生成键值对,但是如何将“Timestamp”的值复制到每个记录中?

[{
  "operation": "shift",
  "spec": {
    "Timestamp": "[].Timestamp",
    "*": {
      "$": "[#2].key",
      "@": "[#2].value"
    }
  }
}]

上述JOLT规范的输出:

[ {
  "Timestamp" : "2018-05-13T14:57:09"
}, {
  "key" : "first_key",
  "value" : "1023"
}, {
  "key" : "another_key",
  "value" : "1987"
}, {
  "key" : "yet_another_key",
  "value" : "677"
} ]

1 个答案:

答案 0 :(得分:1)

规格

[
  {
    // first separate the Timestamp from the fields that 
    //  are going to be pivoted.
    // This is needed because the "[#2]" logic 
    //  isn't doing what you think it is / 
    //  you would end up with a null in your output array.
    // Basically the "[#2]" logic as written only works
    //  when you are cleanly pivoting data.  Which you are
    //  not because "Timestamp" and "first_key" are siblings.
    "operation": "shift",
    "spec": {
      "Timestamp": "Timestamp",
      "*": "keysToPivot.&"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "keysToPivot": {
        "*": {
          // Now that we can cleanly loop thru _only_ the 
          //  keysToPivot, the [#2] logic will work "right".
          // Additionally, lookup the Timestamp value
          //  and add it to each "pivoted" output.
          "$": "[#2].key",
          "@": "[#2].value",
          "@(2,Timestamp)": "[#2].Timestamp"
        }
      }
    }
  }
]