Issue
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
Solution
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) )
As @glennjackman mentions in a comment, the above construct will have problems if your keys contain whitespace or shell special characters. For example, given this data:
{
"employee*" : {
"aliases" : { }
}
}
If your directory contains files named employee1
and employee2
, then you'll get, effectively:
myarray=( employee1 employee2 )
...which is not what you want. You can fix this by using the mapfile
builtin (also known as readarray
, which makes its purpose more obvious):
mapfile -t myarray < <(jq -r 'keys[]' data.json)
Answered By - larsks Answer Checked By - Mary Flores (WPSolving Volunteer)