使用jq基于对象中变量的值选择对象

时间:2013-09-03 12:19:32

标签: json bash jq

我有以下json文件:

{
    "FOO": {
        "name": "Donald",
        "location": "Stockholm"
    },
    "BAR": {
        "name": "Walt",
        "location": "Stockholm"
    },
    "BAZ": {
        "name": "Jack",
        "location": "Whereever"
    }
}

我正在使用jq并希望得到'location'为'Stockholm'的对象的“name”元素。

我知道我可以通过

获得所有名字
cat json | jq .[] | jq ."name"
"Jack"
"Walt"
"Donald"

但考虑到子键的值(此处为"location" : "Stockholm"),我无法弄清楚如何仅打印某些对象。

4 个答案:

答案 0 :(得分:238)

经过大量谷歌搜索主要发现jQuery的东西,我发现了一篇博文,其中包含答案:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

从这里开始:http://zerokspot.com/weblog/2013/07/18/processing-json-with-jq/

答案 1 :(得分:123)

获取名称的流:

$ jq '.[] | select(.location=="Stockholm") | .name' json

产生

"Donald"
"Walt"

要获取相应的(键名,"名称和#34;属性)对的流,请考虑:

$ jq -c 'to_entries[]
        | select (.value.location == "Stockholm")
        | [.key, .value.name]' json

输出:

["FOO","Donald"]
["BAR","Walt"]

答案 2 :(得分:23)

我有一个类似的相关问题:如果您想要原始对象格式(使用键名,例如FOO,BAR)怎么办?

Jq提供to_entriesfrom_entries来转换对象和键值对数组。这与选择

周围的map一起
  

这些函数在对象和键值数组之间进行转换   对。如果to_entries是传递一个对象,那么对于每个k:v条目   输入,输出数组包括{“key”:k,“value”:v}。

     

from_entries执行相反的转换,而with_entries(foo)是a   to_entries的简写| map(foo)| from_entries,对做有用   对对象的所有键和值的一些操作。 from_entries   接受键,键,名称,名称,值和值作为键。

jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'

{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

使用with_entries简写,这将成为:

jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

答案 3 :(得分:2)

只需尝试将其作为完整副本粘贴到外壳中,您就可以掌握

# create the example file to  be working on .. 
cat << EOF > tmp.json
[  
 { "card_id": "id-00", "card_id_type": "card_id_type-00"},
 {"card_id": "id-01", "card_id_type": "card_id_type-01"},
 {  "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF


# pipe the content of the file to the  jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'

id-01

或使用aws cli命令

 # list my vpcs or
 # list the values of the tags which names are "Name" 
 aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort  -nr