简体   繁体   English

在JQ中按字段选择对象并打印父键

[英]Select object by field and print parent key in JQ

I'm looking to find a way to pull the parent key name from a JSON list that looks something like this:我正在寻找一种方法从 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" 
    }
}

Parent keys in this case are server names, and want to use JQ by to pull these over by selecting a specific country.在这种情况下,父键是服务器名称,并且希望通过选择特定国家来使用 JQ by 来提取这些名称。 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!非常感谢您的建议和专业知识!

to_entries[] | select( .value.country_short == "gb" ) | .key

jqplay上的演示

Here is one way:这是一种方法:

path(.[] | select(.country == "United Kingdom"))[0]

Online demo在线演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM