Jq: How to group and merge object

Created on 22 Jan 2014  路  1Comment  路  Source: stedolan/jq

Hi,
I have this input document:

 [
    {
      "id": "308075507",
      "varId": "334035522-M24"
    },
    {
      "id": "308075507",
      "varId": "334035522-M48"
    }
  ]

and I want to transform it into

 [
    {
      "id": "308075507",
      "varId": ["334035522-M24", "334035522-M48"]
    }
  ]

If that is not possible, perhaps the following problem can be solved easier:
I want to select specific fields from an input document:
Input:

{
  "id": "308075507",
  "uninterestingField":"blah"
  variations : [
    {
       "varId": "334035522-M24"
       "uninterestingField":"blah"
    },
    {
       "varId": "334035522-M48"
       "uninterestingField":"blah"
    }
  ]
}

I just want the same json structure without the uninteresting fields.
Currently I am doing this:

jq  '[{id, varId: .variations.variation[].varId}]'

But that splits the document in two documents:

 [
    {
      "id": "308075507",
      "varId": "334035522-M24"
    },
    {
      "id": "308075507",
      "varId": "334035522-M48"
    }
  ]

Thanks for your help.

support

Most helpful comment

I was lurking through the query label and found this issue. Better late than never, I guess!

For your first question, you want to use group_by. Taking the first JSON sample as input:

group_by(.id) | map({"id": .[0].id, "varId": map(.varId)})

For your second question: the reason why the document is "split" is that you're breaking up the array on variation[] and then collecting the results with the brackets that surround the whole object. I get the feeling that you want to collect the results around varId's value instead:

'{id, varId: [.variations.variation[].varId]}'

>All comments

I was lurking through the query label and found this issue. Better late than never, I guess!

For your first question, you want to use group_by. Taking the first JSON sample as input:

group_by(.id) | map({"id": .[0].id, "varId": map(.varId)})

For your second question: the reason why the document is "split" is that you're breaking up the array on variation[] and then collecting the results with the brackets that surround the whole object. I get the feeling that you want to collect the results around varId's value instead:

'{id, varId: [.variations.variation[].varId]}'

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mcandre picture mcandre  路  3Comments

thelonious picture thelonious  路  4Comments

rubensayshi picture rubensayshi  路  3Comments

kelchy picture kelchy  路  4Comments

neowulf picture neowulf  路  3Comments