I'm looking to find a way to pull the parent key name from a JSON list that looks something like this:
{
"london1.perfect-privacy.com": {
"city": "London",
"city_short": "lo",
"country": "United Kingdom",
"country_short": "gb",
"lati": "51.511214",
"longi": "-0.119824"
},
"london2.perfect-privacy.com": {
"city": "London",
"city_short": "lo",
"country": "United Kingdom",
"country_short": "gb",
"lati": "51.511214",
"longi": "-0.119824"
},
"rotterdam2.perfect-privacy.com": {
"city": "Rotterdam",
"city_short": "ro",
"country": "Netherlands",
"country_short": "nl",
"lati": "51.924216",
"longi": "4.481776"
}
}
Parent keys in this case are server names, and want to use JQ by to pull these over by selecting a specific country. This code below lets me pull all the parent keys, but I'm having trouble narrowing it down to just those that belong to a specific country:
jq -r 'keys' serverlocations.json
Results:
london1.perfect-privacy.com
london2.perfect-privacy.com
rotterdam2.perfect-privacy.com
So when I try something like this, I get a big fat error...
jq -r 'keys | select(.country == "United Kingdom")' serverlocations.json"
Error:
jq: error (at <stdin>:0): Cannot index array with string "country"
I would have expected and want these results back:
london1.perfect-privacy.com
london2.perfect-privacy.com
Your advice and expertise is greatly appreciated!
CodePudding user response:
Here is one way:
path(.[] | select(.country == "United Kingdom"))[0]
CodePudding user response:
to_entries[] | select( .value.country_short == "gb" ) | .key
Demo on jqplay