jq example
介绍 当我们想在 Shell 脚本中解析 Json 文件时,我们通常会使用 jq 工具。本文记录一些使用 jq 的方法,基本上可以用来解析所有 Json 的特性。 本篇文章测试 Json 文件 基础用法 解析字段 # 输出 json 格式 jq -c '.value1' < jq_example.json # 输出 raw string jq -r '.value1' < jq_example.json jq -r '.value2.value21' < jq_example.json jq -r '.value2.value22.value221' < jq_example.json 判断字段是否存在 $ jq 'has("value1")' < jq_example.json true $ jq 'has("value10")' < jq_example.json false 进阶用法 解析数组 #! /usr/bin/env bash readarray -t array1 <<<"$(jq -c '.array1[]' < jq_example.json)" for a in "${array1[@]}" do echo $a done 解析数组中的 Json 对象 #! /usr/bin/env bash readarray -t array2 <<<"$(jq -c '.array2[]' < jq_example.json)" for a2 in "${array2[@]}" do echo $a2 | jq -r '.name' echo $a2 | jq -r '.value' done