cat animals.json
{
"animals":[
{
"name": "cat",
"say":"meow",
"types": [
{ "name": "Scottish Fold", "origin": "Scotland" },
{ "name": "Munchkin", "origin": "United States" },
{ "name": "Norwegian Forest Cat", "origin": "Norway" }
]
},{
"name": "dog",
"say":"bowwow",
"types": [
{ "name": "Toy Poodle", "origin": "France" },
{ "name": "Chihuahua", "origin": "Mexico" },
{ "name": "Shiba Inu", "origin": "Japan" }
]
}
]
}
cat animals.json | jq .
{
"animals": [
{
"name": "cat",
"say": "meow",
"types": [
{
"name": "Scottish Fold",
"origin": "Scotland"
},
{
"name": "Munchkin",
"origin": "United States"
},
{
"name": "Norwegian Forest Cat",
"origin": "Norway"
}
]
},
{
"name": "dog",
"say": "bowwow",
"types": [
{
"name": "Toy Poodle",
"origin": "France"
},
{
"name": "Chihuahua",
"origin": "Mexico"
},
{
"name": "Shiba Inu",
"origin": "Japan"
}
]
}
]
}
cat animals.json | jq '.animals[]'
{
"name": "cat",
"say": "meow",
"types": [
{
"name": "Scottish Fold",
"origin": "Scotland"
},
{
"name": "Munchkin",
"origin": "United States"
},
{
"name": "Norwegian Forest Cat",
"origin": "Norway"
}
]
}
{
"name": "dog",
"say": "bowwow",
"types": [
{
"name": "Toy Poodle",
"origin": "France"
},
{
"name": "Chihuahua",
"origin": "Mexico"
},
{
"name": "Shiba Inu",
"origin": "Japan"
}
]
}
cat animals.json | jq '.animals[].name'
"cat"
"dog"
cat animals.json | jq -r '.animals[].name'
cat
dog
cat animals.json | jq -r '.animals[] | "TYPE="+.name+"; SAY="+.say'
TYPE=cat; SAY=meow
TYPE=dog; SAY=bowwow
cat animals.json | jq '.animals[] | select(.name=="cat")'
{
"name": "cat",
"say": "meow",
"types": [
{
"name": "Scottish Fold",
"origin": "Scotland"
},
{
"name": "Munchkin",
"origin": "United States"
},
{
"name": "Norwegian Forest Cat",
"origin": "Norway"
}
]
}
cat animals.json | jq -r '.animals[] | select(.name=="cat") | .types[] | select(.origin | test("United")) | .name'
Munchkin
cat animals.json | jq -r '.animals[] | select(.name=="dog") | .types[] | select(.name | test("Shiba")) | .origin'
Japan
CatにRussian Blueを追加、結局Animalsを再構築している。いい方法が見つからない。
jq -sr '.[].animals[] | select(.name=="cat") | .types |= .+[{"name":"Russian Bule","origin":"Russia"}]' animals.json > cat.json
jq -sr '.[].animals[] | select(.name!="cat")' animals.json > notcat.json
jq -s '.[0]*{"animals":[.[1],.[2]]}' animals.json cat.json notcat.json
こうするといいっぽい。カッコでかこった部分が式として評価される(.の結果が変わらない)。
jq -s '(.[].animals[] | select(.name=="cat") | .types) |= .+[{"name":"Russian Blue","origin":"Russia"}]' animals.json