jq cheatsheet
安装
brew install jq # macOS
apt-get install jq # Debian/Ubuntu
zypper in jq # OpenSUSE
dnf install jq
pacman -S jq
chocolatey install jq
取值
echo '{
"string": "Hello, world!",
"number": 233,
"object": {
"key": "value"
},
"string-array": ["Ubuntu", "Deepin", "OpenSUSE", "CentOS"],
"object-array": [{
"key": "value"
}]
}' > tmp.json
cat tmp.json | jq .string #> "Hello, world!"
cat tmp.json | jq .string -r #> Hello, world!
cat tmp.json | jq .number #> 233
cat tmp.json | jq .object
{
"key": "value"
}
cat tmp.json | jq '."string-array"'
[
"Ubuntu",
"Deepin",
"OpenSUSE",
"CentOS"
]
cat tmp.json | jq '."string-array"[0]' #> "Ubuntu"
cat tmp.json | jq '."object-array"[0]'
{
"key": "value"
}
cat tmp.json | jq '."object-array"[0].key' #> "value"
cat tmp.json | jq '. | keys'
[
"number",
"object",
"object-array",
"string",
"string-array"
]
cat tmp.json | jq '. | keys | length' #> 5
echo '{
"string": "Hello, world!",
"number": 233,
"object": {
"key": "value"
},
"string-array": ["Ubuntu", "Deepin", "OpenSUSE", "CentOS"],
"object-array": [{
"key": "value"
}]
}' > tmp.json
cat tmp.json | jq .string #> "Hello, world!"
cat tmp.json | jq .string -r #> Hello, world!
cat tmp.json | jq .number #> 233
cat tmp.json | jq .object
{
"key": "value"
}
cat tmp.json | jq '."string-array"'
[
"Ubuntu",
"Deepin",
"OpenSUSE",
"CentOS"
]
cat tmp.json | jq '."string-array"[0]' #> "Ubuntu"
cat tmp.json | jq '."object-array"[0]'
{
"key": "value"
}
cat tmp.json | jq '."object-array"[0].key' #> "value"
cat tmp.json | jq '. | keys'
[
"number",
"object",
"object-array",
"string",
"string-array"
]
cat tmp.json | jq '. | keys | length' #> 5
获取 JSON 对象的所有键值
echo '{
"id": "001",
"name": "Apple",
"size": "large",
"vendor": "N/A"
}' | jq -r ' keys[]'
获取指定数组元素
** JSON Array: 根据 name 获得对应 id 的值
echo '[
{ "id": "001", "name": "Apple" },
{ "id": "002", "name": "Banana" }
]' | jq -r '.[] | select(.name == "Apple") | .id'
** JSON Object: 根据 name 获得对应 id 的值
echo '{
"001": { "name": "Apple" },
"002": { "name": "Banana" }
}' | jq -r 'keys[] as $k | select(.[$k].name == "Apple") | "\($k)" '
修改
修改字符串
echo '{
"value": "hello"
}' > tmp.json
替换字符串
jq '.value = "hey"' tmp.json
拼接字符串
jq '.value += ", world"' tmp.json
修改 JSON Object
echo '{
"value": "hello"
}' > tmp.json
添加字段
jq '.version = "v1"' tmp.json
删除字段
jq 'del(.value)' tmp.json
N/A
修改 JSON Array
参数化
echo '{}' | jq --arg NAME "Apple" --arg COLOR "Red" ' .name = $NAME | .color = $COLOR '