Useful Link:
offical manual link:jq Manual (development version)
常用操作:jq 常用操作 - Huang Huang 的博客
处理实例:Shell:无比强大的shell之json解析工具jq , Linux命令行解析json, jq解析 json 实例
JSON格式化输出和解析工具 - jq - 散尽浮华 - 博客园
code:GitHub - stedolan/jq: Command-line JSON processor
other than jq, 用sh脚本直接处理json:https://github.com/dominictarr/JSON.sh
1. ubuntu安装:sudo apt-get install jq
2. 查看jq帮助:man jq
3. 传输参数 :--arg
arg="configuration1"
jq --arg arg "$arg" '.configurations[] | select(.name == $arg)' example.json
4. 以指定的格式打印json的key和value:keys[] as $k(-r 去掉双引号,即从“a”->a)
jq -r '.[] | keys[] as $k | "--\($k)=\(.[$k])"' example.json
5. 合并多个json文件:
jq -r -s '.[0] * .[1]' file1 file2
echo '{"A": {"a": 1}}' '{"A": {"b": 2}}' '{"B": 3}' |\
jq --slurp 'reduce .[] as $item ({}; . * $item)'
6. 遍历json数组:
jq -c '.[test_group_1][]' example.json | while read test; do
echo "test $test"
done
7. 更改某一字段的数值:
jq '.test_group_1[] | select(.name == test_1-1).checksum = 1' example.json
8. 更改某一字段的key:with_entries( is equal to "from_entries, map, to_entries")
jq '. |= with_entries(.key |= sub("^test_group_1$"; "changed"))' example.json
example.json
{
"configurations": [
{
"name": "configuration1",
"parameters": {
"itype": "xxx"
}
}
],
"test_group_1": [
{
"name": "test_1-1",
"config": "configuration1",
"file": "testfile3",
"checksum": "8a9d260e03e95e1b10a474bf82ed8ac7"
},
{
"name": "test_1-2",
"ignore": true,
"config": "configuration1",
"file": "testfile3",
"parameters": {
"duration": "70000"
},
"checksum": "d4622236d60df0098cc85861bc089e3f"
}
]
}