Home > Software engineering >  Put JSON keys in a shell script array
Put JSON keys in a shell script array

Time:07-19

I need to put the json keys of a file as a array in a shell script how can i do that?

{
  "employee4" : {
    "aliases" : { }
  },
  "employee3" : {
    "aliases" : { }
  },
  "employee" : {
    "aliases" : { }
  },
  "employee2" : {
    "aliases" : { }
  }
}

I need to have a array like keys["employee", "employee2", "employee3", "employee4"] If there is more keys the array need to find them

CodePudding user response:

The jq keys function returns a list of keys. So with your example data in data.json, we see:

$ jq 'keys' data.json
[
  "employee",
  "employee2",
  "employee3",
  "employee4"
]

To get rid of the JSON list, we run:

$ jq -r 'keys[]' data.json
employee
employee2
employee3
employee4

And to get that into a bash array:

myarray=( $(jq -r 'keys[]' data.json) )
  • Related