1. 简介
记录jq-1.7
常用语法。
2. 用例
示例json
example.json
1
2
3
4
5
| {
"name": "example",
"hash": "0c716eee2da840c54",
"command": "bash jenkins.sh"
}
|
2.1 输出,返回原始值
jq默认返回JSON-TEXTS(带引号), 可通过 -r
获取原始字符串
1
2
3
4
| jq -r '.name' ./example.json
# 或者
echo echo '{"name": "example"}' | jq -r .name
|
默认返回值(带引号)为"example"
, 增加-r
返回值为example
。
2.1 jq解析,压缩返回值
2.2 jq解析,优雅输出
2.3 jq拼接json对象
-n 创建一个空对象,通常
使用函数fromjson
,将字符串对象解析为json对象
1
| jq -n --arg s "example strings" --arg obj "$(jq . b.json)" '{"str": $s, "object": $obj|fromjson}' > result.json
|
或者,使用--argjson
确保$obj
被当作json对象处理。
1
| jq -n --arg s "example strings" --argjson obj "$(jq . b.json)" '{"str": $s, "object": $obj}' > result.json
|
json文件内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| jq . b.json
{
"main_hash": "0c716eee2da840c54",
"params_hash": "0c716eee2da840c54",
"command": "bash jenkins.sh"
}
jq 。result.json
{
"str": "example strings",
"object": {
"main_hash": "0c716eee2da840c54",
"params_hash": "0c716eee2da840c54",
"command": "bash jenkins.sh"
}
}
|
2.4
参考链接