[每日短篇]27在Shell脚本或命令行中操作Json
现在使用 json 或者 yaml 格式的配置文件越来越普遍,而编写 shell 脚本经常需要操作配置文件,这就产生一个新问题:如何操作这些格式的配置文件。本文先解决操作 json 文件的问题。下面列出常见的一些操作,其它操作可以照此办理。作者推荐的 Linux 发行版仍然是 Ubuntu,即使在 Ubuntu Cloud Image 中下面的操作都可以直接执行而不需安装额外的包。
添加值
以给 docker 添加 mirror 为例,配置文件为 json 格式,给 json 添加一个名为 registry-mirrors
的属性。
# $1="["registry.docker.io"]"echo -e "import json;arr = json.loads("$1");j = json.load(open("/etc/docker/daemon.json"));
j["registry-mirrors"]=arr;print(json.dumps(j))" | python3 > /etc/docker/daemon.json
删除值
还是以 docker 配置文件为例,把刚添加到 json 配置文件中的属性删掉
echo -e "import json;j = json.load(open("/etc/docker/daemon.json"));if "registry-mirrors" in j: del j["registry-mirrors"];print(json.dumps(j))" | python3 > /etc/docker/daemon.json
提取值
继续以 docker 配置文件为例,读取 json 文件查询属性的值
echo -e "import json;j = json.load(open("/etc/docker/daemon.json"));if "registry-mirrors" in j: print(j["registry-mirrors"])" | python3
需要注意的是上面几个操作都是针对 json 对象操作的,尤其对数组操作时不能简单当作字符串处理(参考添加值的例子)。
格式化输出 json
cat /etc/docker/daemon.json | python3 -m json.tool
如果要对 key
排序输出可添加 --sort-keys
参数
cat /etc/docker/daemon.json | python3 -m json.tool --sort-keys
上面几种操作已经覆盖了大多数场景,没有覆盖的场景使用上面两个工具也很容易解决。如果非要复杂的处理又不想写一段 python 代码解决,那还可以考虑使用 jq
软件包,sudo apt-get install jq
安装占用大约 1M 空间,docker 镜像中的首选。常用命令
添加值
cat /etc/docker/daemon.json | jq -c ". + {"registry-mirrors":$1}" > /etc/docker/daemon.json
删除值
cat /etc/docker/daemon.json | jq -c "del(."registry-mirrors")" > /etc/docker/daemon.json
提取值
cat /etc/docker/daemon.json | jq -c "."registry-mirrors""cat /etc/docker/daemon.json | jq -c "."registry-mirrors"[0]"
格式化输出 json
# pretty 格式cat /etc/docker/daemon.json | jq
# compact 格式
cat /etc/docker/daemon.json | jq -c
上面命令基于字符串处理,数组和字符串靠自己加或者不加引号处理。
以上是 [每日短篇]27在Shell脚本或命令行中操作Json 的全部内容, 来源链接: utcz.com/z/517066.html