jq transform - json child array objects to delimited string

时间:2018-12-03 13:01:28

标签: json jq

i want to transform the following input with jq

{
   "root":[
      {
         "field1":"field1value1",
         "field2":"field2value2",
         "field3Array":[
            {
               "prop1":"prop1_value1"
            }
         ]
      },
      {
         "field1":"field1value3",
         "field2":"field2value4",
         "field3Array":[
            {
               "prop1":"prop1_value3"
            },
            {
               "prop1":"prop1_value4"
            }
         ]
      }
   ]
}

Output should be:

[
  {
    "field1": "field1value1",
    "field2": "field2value2",
    "field3Array": "prop1_value1"
  },
  {
    "field1": "field1value3",
    "field2": "field2value4",
    "field3Array": "prop1_value3,prop1_value4"
  }
]

I use this jq filter so far -> "[.root[] | {field1, field2, field3Array: .field3Array[].prop1}]" but don't know howto "join" the array property "prop1" to a comma delimited string -> "prop1_value3,prop1_value4"

https://jqplay.org/s/CR8mGBX8Dz

1 个答案:

答案 0 :(得分:1)

您需要将field3Array中包含的对象映射到它们的字符串值,并加入结果数组:

.root | map({field1, field2, field3Array: .field3Array | map(.prop1) | join(",")})

您可以here试试。


在下面的示例中,我们可以就地更新.field3Array而不是重新创建整个对象,从而可以对其进行简化:

.root | map(.field3Array |= (map(.prop1) | join(",")))

您可以here试试。


如果您不熟悉map函数,则下面的方法也可以工作:

[.root[] | {field1, field2, field3Array: [ .field3Array[] | .prop1 ] | join(",")}]

您可以here试试。