1

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 I don't know how to join the array property "prop1" to a comma-delimited string "prop1_value3,prop1_value4".

https://jqplay.org/s/CR8mGBX8Dz

1 Answer 1

1

You need to map the objects contained in the field3Array to their string values and join the resulting array :

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

You can try it here.


It can be somewhat simplified in the following where we update the .field3Array in-place instead of recreating a whole object :

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

You can try it here.


If you're unfamiliar with the map function, the following would have worked as well :

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

You can try it here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.