jq transform-将json子数组转换为定界字符串

时间:2018-11-21 12:51:49

标签: json jq

我想用jq转换以下输入

{
    "count": 1000,
    "rows": [{
            "id": 1,
            "child_id": 11,
            "childarray": ["value1", "value2"]
        },
        {
            "id": 2,
            "child_id": 12,
            "childarray": ["value3", "value4"]
        }
    ]
}

输出应为:

[
  {
    "id": 1,
    "child_id": 11,
    "childarray": "value1, value2"
  },
  {
    "id": 2,
    "child_id": 12,
    "childarray": "value3, value4"
  }
]

我使用此jq过滤器->“ [.rows[]]”,但不知道如何将数组“连接”-> "childarray": ["value1", "value2"]到逗号分隔的字符串->“ value1, value2” < / p>

https://jqplay.org/s/5TlSDgJnkc

1 个答案:

答案 0 :(得分:1)

map + join方法:

jq '.rows | map(.childarray |= join(", "))' input.json

输出:

[
  {
    "id": 1,
    "child_id": 11,
    "childarray": "value1, value2"
  },
  {
    "id": 2,
    "child_id": 12,
    "childarray": "value3, value4"
  }
]

另一种选择是:

jq '.rows[].childarray |= join(", ") | .rows'