json - 如何循环来自bash脚本的json键结果

标签 json bash jq

input.json:-

{
"menu": {
  "id": "file",
  "value": "File",
  "user": {
    "address": "USA",
    "email": "user@gmail.com"
  }
}
}

命令:-

result=$(cat input.json | jq -r '.menu | keys[]')

结果:-

id
value
user

遍历结果:-

for type in "${result[@]}"
do
    echo "--$type--"
done

输出:-

--id
value
user--

我想在循环中处理键值。当我执行上述操作时,结果为单个字符串。

如何使用 json 键循环生成 bash 脚本?

最佳答案

规范的方式:

file='input.json'
cat "$file" | jq -r '.menu | keys[]' | 
while IFS= read -r value; do
    echo "$value"
done

bash faq #1


但你似乎想要一个数组,所以语法是(缺少括号):

file='input.json'

result=( $(cat "$file" | jq -r '.menu | keys[]') )

for type in "${result[@]}"; do
    echo "--$type--"
done

输出:

--id--
--value--
--user--

关于json - 如何循环来自bash脚本的json键结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49382979/

相关文章:

bash - shell 脚本 : insert string below a line depending on line number

linux - 将可用 Windows 服务列表传递到数组中并提示用户选择要激活的服务

json - jq:将对象数组转换为单个对象并将每个数组索引用作新键

json - 我如何制作这个 jq 表达式,它适用于 jq >= 1.5,对于 < 1.5 的版本向后兼容/正确

jq:错误:无法遍历字符串

javascript - 从 angularjs 表单生成 json

arrays - 通过 JSON 将对象数组发布到 ASP.Net MVC3

java - 使用 GSON 解析带有键和选项卡的 JSON 文件

bash - 在 Bash shell 中锁定 ‘set +e’

android - 无法在 SwipeFlingAdapterView 中显示项目