我有一个在JSON中获取数据的Bash脚本,我希望能够convert the JSON into an accessible structure数组/列表/或其他模型,这将很容易解析嵌套的数据.

Example:

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

我想得到如下值:echo ${arr[SOMETHING]}

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

推荐答案

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

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

Json相关问答推荐

将数组中的值作为键连接到另一个数组中的值(Jolt)

如何将文件夹组织的.json文件合并为一个JSON文件,文件夹/文件名作为键

使用 jq 如何更改键的值?

Jolt规范:将嵌套数组中的null元素移除

从字节解码 JSON 数据,将 float 值更改为 int

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

在 json 嵌入的 YAML 文件中 - 使用 Python 仅替换 json 值

如何使用 Swiftui 判断 JSON 是否缺少键值对

Play Framework:如何序列化/反序列化与 JSON 的枚举

解析包含换行符的 JSON

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

JSON RPC - 什么是id?

在 Apache Spark 中读取多行 JSON

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

以 unicode 将 pandas DataFrame 写入 JSON

jQuery JSON 响应总是触发 ParseError

如何在 Python 中合并两个 json 字符串?

JSON JQ 如果没有 else

有没有办法折叠 Postman 中的所有 json 字段

类型是接口或抽象类,不能实例化