- 已编辑
Shell jq 命令行的常用方法
将 JSON 转为 key=value&key2=value2
{ "aaa": "v1", "bbb": "v2", "ccc": "v3" }
aaa=v1&bbb=v2&ccc=v3
echo '{"aaa": "v1", "bbb": "v2", "ccc": "v3"}' | jq -r 'to_entries | map("\(.key)=\(.value)") | join("&")'
处理编码
echo '{"aaa": "v1", "bbb": false, "ccc": null}' | jq -r 'to_entries | map("\(.key)=\(.value // "")") | join("&")'
aaa=hello%20world&bbb=a%26b%3Dc```
去除参数值为空的键名
echo '{"aaa": "v1", "bbb": "v2", "ccc": ""}' | jq 'with_entries(select(.value != ""))'
{ "aaa": "v1", "bbb": "v2" }
提取多个字段
[ { "id": 1, "name": "project1", "description": "This is project 1", "created_at": "2023-01-01" }, { "id": 2, "name": "project2", "description": "This is project 2", "created_at": "2023-02-01" }, { "id": 3, "name": "project3", "description": "This is project 3", "created_at": "2023-03-01" } ]
echo '[{"id":1,"name":"project1","description":"This is project 1","created_at":"2023-01-01"},{"id":2,"name":"project2","description":"This is project 2","created_at":"2023-02-01"},{"id":3,"name":"project3","description":"This is project 3","created_at":"2023-03-01"}]' | jq -r '.[] | (.id, .name)'
1 project1 2 project2 3 project3
提取多个字段,分组
echo '[{"id":1,"name":"project1","description":"This is project 1","created_at":"2023-01-01"},{"id":2,"name":"project2","description":"This is project 2","created_at":"2023-02-01"},{"id":3,"name":"project3","description":"This is project 3","created_at":"2023-03-01"}]' | jq '.[] | {id, name}'
{ "id": 1, "name": "project1" } { "id": 2, "name": "project2" } { "id": 3, "name": "project3" }
插入文字
如果是数组[{"name": "Alice"}, {"name": "Bob"}, {"name": "Charlie"}]
jq '"数量有 " + (length|tostring) + " 个"' data.json
如果是对象
{"name": "Alice"}, {"name": "Bob"}, {"name": "Charlie"}
jq '"对象中有 " + (keys | length | tostring) + " 个键"' data.json