Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jq to create an object with an arbitrary key from a sub array?

Tags:

json

jq

Please feel free to edit the title, I am not sure how to best express it :).

I have JSON that, for example, looks like this:

{
  "things": [
     {
        "name": "foo",
        "params": [
           {
             "type": "t1",
              "key": "key1",
              "value": "val1"
           },
           {
              "type": "t1",
              "key": "category",
              "value": "thefoocategory"
           }
        ]
      },
      {
        "name": "bar",
        "params": [
           {
             "type": "t1",
             "key": "key1",
             "value": "val1"
           },
           {
             "type": "t1",
             "key": "category",
             "value": "thebarcategory"
           }
        ]
     }
  ]
}

What I am trying to achieve is output that looks like

[
  {
    name: "foo",
    category: "thefoocategory"
  },
  {
    name: "bar",
    category: "thebarcategory"
  }
]

I am able to extract the names quite easily with jq ' .things | .[] | .name'

I can also extract the categories with jq ' .things | .[] | .params | .[] | select(.key == "category") | .value'

But I have not been able to combine them.

Any help appreciated

like image 479
geoff Avatar asked Jun 16 '16 16:06

geoff


2 Answers

This was actually relatively straight forward:

.things | .[] | {name: .name, category: .params | .[] | select(.key=="category") | .value }
like image 121
geoff Avatar answered Oct 10 '22 01:10

geoff


Your params almost looks like key/value entries, so you could create an object out of them by passing the array to from_entries. So to combine everything, you merely need to do this:

.things | map({name} + (.params | from_entries))

This yields:

[
  {
    "name": "foo",
    "key1": "val1",
    "category": "thefoocategory"
  },
  {
    "name": "bar",
    "key1": "val1",
    "category": "thebarcategory"
  }
]
like image 34
Jeff Mercado Avatar answered Oct 10 '22 01:10

Jeff Mercado