Home > database >  How to access a json value within an object that has different named keys with jq
How to access a json value within an object that has different named keys with jq

Time:04-03

I have data that looks like this:

{
  "Object0" : {
    "data01" : "value01",
    "data02" : "value02",
    "data03" : "value03",
    "data04" : "value04"
  },
  "Object1" : {
    "data11" : "value11",
    "data12" : "value12",
    "data13" : "value13",
    "data14" : "value14"
  },
  "variables": {
    "variable1": {
      "isSecret": null,
      "value": "value1"
    },
    "variable2": {
      "isSecret": null,
      "value": "value2"
    },
    "variable3": {
      "isSecret": null,
      "value": "value3"
    },
    "variable4": {
      "isSecret": null,
      "value": "value4"
    }
  }
}

I am trying to grab the variable names and the values, using jq. I want output that links the two together in any form of structured data. Something that would look/function similar to:

varible1,value1
varible2,value2
varible3,value3
varible4,value4

It could be json, csv or tsv. Whatever you have is great.

Right now I am only able to get to the variable names with:

$ cat data.json | jq -r '.variables | keys[]'
variable1
variable2
variable3
variable4

I was also able to begin to create json key/value pairs with:

$ cat data.json | jq -r '{(.variables | keys[]):"42"}'
{
  "variable1": "42"
}
{
  "variable2": "42"
}
{
  "variable3": "42"
}
{
  "variable4": "42"
}

But I'm still not able to access those sweet values.

I've been reading through the man pages and I tried using recurse, walk, foreach, recursive descent, and a few others. I did not realize how robust jq is! It's now one of my favorite bash utilities. But I've still got this problem. Can anyone shed some light on this?

CodePudding user response:

Using to_entries:

jq -r '.variables | to_entries[] | [ .key, .value.value ] | @csv'

Using keys:

jq -r '.variables | keys[] as $k | [ $k, .[$k].value ] | @csv'
  • Related