在Bash中访问JSON对象-关联数组/列表/另一个模型 [英] Accessing a JSON object in Bash - associative array / list / another model

查看:102
本文介绍了在Bash中访问JSON对象-关联数组/列表/另一个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Bash脚本,它以JSON格式获取数据,我希望能够将JSON转换为可访问的结构-数组/列表/或其他易于解析嵌套的模型数据.

I have a Bash script which gets data in JSON, I want to be able to convert the JSON into an accessible structure - array / list / or other model which would be easy to parse the nested data.

示例:

{
  "SALUTATION": "Hello world",
  "SOMETHING": "bla bla bla Mr. Freeman"
}

我想要获取如下所示的值:echo ${arr[SOMETHING]}

I want to get the value like the following: echo ${arr[SOMETHING]}

[不同的方法也是可选的. ]

[ Different approach is optional as well. ]

推荐答案

如果您想要键和值,并且基于我如何将JQ中的json对象转换为key = value格式,您可以执行以下操作:

If you want key and value, and based on How do i convert a json object to key=value format in JQ, you can do:

$ jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" file
SALUTATION=Hello world
SOMETHING=bla bla bla Mr. Freeman

以更一般的方式,您可以像这样将值存储到数组myarray[key] = value中,只需使用while ... do; ... done < <(command)语法为while提供jq即可:

In a more general way, you can store the values into an array myarray[key] = value like this, just by providing jq to the while with the while ... do; ... done < <(command) syntax:

declare -A myarray
while IFS="=" read -r key value
do
    myarray[$key]="$value"
done < <(jq -r 'to_entries|map("(.key)=(.value)")|.[]' file)

然后您可以遍历像这样的值:

And then you can loop through the values like this:

for key in "${!myarray[@]}"
do
    echo "$key = ${myarray[$key]}"
done

对于此给定的输入,它将返回:

For this given input, it returns:

SALUTATION = Hello world
SOMETHING = bla bla bla Mr. Freeman

这篇关于在Bash中访问JSON对象-关联数组/列表/另一个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆