Select JQ中按字段打印父键的对象
Select object by field and print parent key in JQ
我正在寻找一种方法来从看起来像这样的 JSON 列表中提取父键名称:
{
"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"
}
}
本例中的父键是服务器名称,并希望通过选择特定国家/地区来使用 JQ by 将它们拉过来。下面的这段代码让我可以提取所有父密钥,但我无法将其缩小到仅属于特定国家/地区的密钥:
jq -r 'keys' serverlocations.json
结果:
london1.perfect-privacy.com
london2.perfect-privacy.com
rotterdam2.perfect-privacy.com
所以当我尝试这样的事情时,我得到了一个大错误...
jq -r 'keys | select(.country == "United Kingdom")' serverlocations.json"
错误:
jq: error (at <stdin>:0): Cannot index array with string "country"
我本来期望并希望得到这些结果:
london1.perfect-privacy.com
london2.perfect-privacy.com
非常感谢您的建议和专业知识!
这是一种方法:
path(.[] | select(.country == "United Kingdom"))[0]
to_entries[] | select( .value.country_short == "gb" ) | .key
Demo 在 jqplay
我正在寻找一种方法来从看起来像这样的 JSON 列表中提取父键名称:
{
"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"
}
}
本例中的父键是服务器名称,并希望通过选择特定国家/地区来使用 JQ by 将它们拉过来。下面的这段代码让我可以提取所有父密钥,但我无法将其缩小到仅属于特定国家/地区的密钥:
jq -r 'keys' serverlocations.json
结果:
london1.perfect-privacy.com
london2.perfect-privacy.com
rotterdam2.perfect-privacy.com
所以当我尝试这样的事情时,我得到了一个大错误...
jq -r 'keys | select(.country == "United Kingdom")' serverlocations.json"
错误:
jq: error (at <stdin>:0): Cannot index array with string "country"
我本来期望并希望得到这些结果:
london1.perfect-privacy.com
london2.perfect-privacy.com
非常感谢您的建议和专业知识!
这是一种方法:
path(.[] | select(.country == "United Kingdom"))[0]
to_entries[] | select( .value.country_short == "gb" ) | .key
Demo 在 jqplay