将JSON对象转换为Bash关联数组 [英] Converting a JSON object into a Bash associative array

查看:119
本文介绍了将JSON对象转换为Bash关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Bash脚本.它以JSON格式获取数据. 我需要将JSON数组转换为Bash数组.

I have a Bash script. It gets data in JSON. I need to convert the JSON array to a Bash array.

示例

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

在Bash中,我想要一个类似echo ${arr[SOMETHING]}的值.

In Bash I want to get a value like this echo ${arr[SOMETHING]}.

推荐答案

如果您想要键和值,并且基于我如何将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

这篇关于将JSON对象转换为Bash关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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