如何将JQ转换为不同的数组,与其他数据联合?

时间:2017-11-21 16:47:08

标签: jq jqtransform

我需要改变这个:

{"input":{"text":"HI"},"output":{"text":["OK1","TWO"]}}

进入这个:

{
  "localDB": [
    {
      "tableName": "Default",
      "mode": "append",
      "data": [
        {
          "time": "1511281401.991815",
          "message": "HI",
          "from": "me"
        },
        {
          "time": "1511281401.991837",
          "message": "OK1"
          "from": "bot"
        }
        {
          "time": "1511281401.991847",
          "message": "TWO"
          "from": "bot"
}
]}]}

有可能吗?

这里的关键问题是"记录的数量"在localDB 中,应根据 .output.text节点中的条目数而有所不同。可能只有一个文本,或三个或更多。

我试过这个,但它不太有效:

{
 "localDB" : [{
   "tableName": "Default",
   "mode": "append",
   "data": [
     {"time" : now|tostring, "message" : .input.text, "from" : "me"},
     {"time" : now|tostring, "message" :.output.text, "from" : "bot"}
  ]
 }]
}

1 个答案:

答案 0 :(得分:0)

我认为你很亲密。您只需使用.output.text[]并利用Object Construction在成员表达式返回多个结果时的行为。试试这个:

{
 "localDB" : [{
   "tableName": "Default",
   "mode": "append",
   "data": [
     {"time" : now|tostring, "message" : .input.text,   "from" : "me"},
     {"time" : now|tostring, "message" :.output.text[], "from" : "bot"}
  ]
 }]
}

示例输出

{
  "localDB": [
    {
      "tableName": "Default",
      "mode": "append",
      "data": [
        {
          "time": "1511283566.11608",
          "message": "HI",
          "from": "me"
        },
        {
          "time": "1511283566.116094",
          "message": "OK1",
          "from": "bot"
        },
        {
          "time": "1511283566.116094",
          "message": "TWO",
          "from": "bot"
        }
      ]
    }
  ]
}

Try it online!

这是一个过滤器,它使用settime函数为行分配不同的时间:

def settime: reduce range(length) as $i (.; .[$i].time = (now + $i|tostring));
{
 "localDB" : [{
   "tableName": "Default",
   "mode": "append",
   "data": [
     {"message" : .input.text,   "from" : "me"},
     {"message" :.output.text[], "from" : "bot"}
   ] | settime
 }]
}

示例输出

{
  "localDB": [
    {
      "tableName": "Default",
      "mode": "append",
      "data": [
        {
          "message": "HI",
          "from": "me",
          "time": "1511285948.684203"
        },
        {
          "message": "OK1",
          "from": "bot",
          "time": "1511285949.684243"
        },
        {
          "message": "TWO",
          "from": "bot",
          "time": "1511285950.684261"
        }
      ]
    }
  ]
}

Try it online!