将JSON对象转换为Bash关联数组

问题描述 投票:13回答:5

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

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

在Bash我希望得到像这样的echo ${arr[SOMETHING]}这样的值。

arrays json bash jq
5个回答
18
投票

如果你想要键和值,并且基于How do i convert a json object to key=value format in JQ,你可以这样做:

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

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

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

然后你可以循环遍历这样的值:

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

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

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

7
投票

上下文:这个答案是为了回应一个不再存在的问题标题而编写的。


OP的问题实际上描述了对象和数组。

但是,为了确保我们帮助其他正在寻求JSON数组帮助的人,它值得明确地覆盖它们。


对于安全的情况,字符串不能包含换行符(当使用bash 4.0或更新时),这有效:

str='["Hello world", "bla bla bla Mr. Freeman"]'
readarray -t array <<<"$(jq -r '.[]' <<<"$str")"

为了支持旧版本的bash和带有换行符的字符串,我们使用NUL分隔的流来读取jq

str='["Hello world", "bla bla bla Mr. Freeman", "this is\ntwo lines"]'
array=( )
while IFS= read -r -d '' line; do
  array+=( "$line" )
done < <(jq -j '.[] | (. + "\u0000")')

3
投票

虽然这个问题得到了解答,但我无法从发布的答案中完全满足我的要求。这是一个小小的写作,它将帮助任何bash-新手。

Foreknowledge

基本的关联数组声明

#!/bin/bash

declare -A associativeArray=([key1]=val1 [key2]=val2)

你也可以在'"declaration周围使用引号(keysvalues)。

#!/bin/bash

declare -A 'associativeArray=([key1]=val1 [key2]=val2)'

你可以通过空格或换行划分每个[key]=value对。

#!/bin/bash

declare -A associativeArray([key1]=value1
  ['key2']=value2 [key3]='value3'
  ['key4']='value2'               ["key5"]="value3"


  ["key6"]='value4'
  ['key7']="value5"
)

根据您的报价变化,您可能需要逃避字符串。

使用Indirection访问关联数组中的键和值

function example {
  local -A associativeArray=([key1]=val1 [key2]=val2)

  # print associative array
  local key value
  for key in "${!associativeArray[@]}"; do
    value="${associativeArray["$key"]}"
    printf '%s = %s' "$key" "$value"
  done
}

运行示例函数

$ example
key2 = val2
key1 = val1

通过了解上述花絮,您可以获得以下片段:


以下示例都将结果作为上述示例

字符串评估

#!/usr/bin/env bash

function example {
  local arrayAsString='associativeArray=([key1]=val1 [key2]=val2)'
  local -A "$arrayAsString"

  # print associative array
}

将JSON管道化为JQ

#!/usr/bin/env bash

function example {
  # Given the following JSON
  local json='{ "key1": "val1", "key2": "val2" }'

  # filter using `map` && `reduce`
  local filter='to_entries | map("[\(.key)]=\(.value)") |
    reduce .[] as $item ("associativeArray=("; . + ($item|@sh) + " ") + ")"'

  # Declare and assign separately to avoid masking return values.
  local arrayAsString;
  arrayAsString=$(cat "$json" | jq --raw-output "${filter}")
  local -A "$arrayAsString"

  # print associative array
}

jq -n / --null-input选项+ --argfile &&重定向

#!/usr/bin/env bash

function example {
  # /path/to/file.json contains the same json as the first two examples
  local filter filename='/path/to/file.json'

  # including bash variable name in reduction
  filter='to_entries | map("[\(.key | @sh)]=\(.value | @sh) ")
    | "associativeArray=(" + add + ")"'

  # using --argfile && --null-input
  local -A "$(jq --raw-output --null-input --argfile file "$filename" \
    "\$filename | ${filter}")"

  # or for a more traceable declaration (using shellcheck or other) this
  # variation moves the variable name outside of the string

  # map definition && reduce replacement
  filter='[to_entries[]|"["+(.key|@sh)+"]="+(.value|@sh)]|"("+join(" ")+")"'

  # input redirection && --join-output
  local -A associativeArray=$(jq --join-output "${filter}" < "${filename}")

  # print associative array
}

查看以前的答案

@JanLalinský

要有效地将JSON对象加载到bash关联数组中(不使用bash中的循环),可以使用工具'jq',如下所示。

# first, load the json text into a variable:
json='{"SALUTATION": "Hello world", "SOMETHING": "bla bla bla Mr. Freeman"}'

# then, prepare associative array, I use 'aa':
unset aa
declare -A aa

# use jq to produce text defining name:value pairs in the bash format
# using @sh to properly escape the values
aacontent=$(jq -r '. | to_entries | .[] | "[\"" + .key + "\"]=" + (.value | @sh)' <<< "$json")

# string containing whole definition of aa in bash
aadef="aa=($aacontent)"

# load the definition (because values may contain LF characters, aadef must be in double quotes)
eval "$aadef"

# now we can access the values like this: echo "${aa[SOMETHING]}"

警告:这使用eval,如果json输入来自未知来源(可能包含eval可能执行的恶意shell命令),这是危险的。

这可以简化为以下内容

function example {
  local json='{ "key1": "val1", "key2": "val2" }'
  local -A associativeArray=("$(jq -r '. | to_entries | .[] |
    "[\"" + .key + "\"]=" + (.value | @sh)' <<< "$json")")

  # print associative array
}

@fedorqui

如果你想要键和值,并且基于How do i convert a json object to key=value format in JQ,你可以这样做:

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

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

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

然后你可以循环遍历这样的值:

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

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

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

这个解决方案和我自己的解决方案之间的主要区别是在bash或jq中循环遍历数组。

每个解决方案都是有效的,根据您的使用情况,一个可能比另一个更有用。


1
投票

这是如何以递归方式完成的:

#!/bin/bash

SOURCE="$PWD"
SETTINGS_FILE="$SOURCE/settings.json"
SETTINGS_JSON=`cat "$SETTINGS_FILE"`

declare -A SETTINGS

function get_settings() {
    local PARAMS="$#"
    local JSON=`jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" <<< "$1"`
    local KEYS=''

    if [ $# -gt 1 ]; then
        KEYS="$2"
    fi

    while read -r PAIR; do
        local KEY=''

        if [ -z "$PAIR" ]; then
            break
        fi

        IFS== read PAIR_KEY PAIR_VALUE <<< "$PAIR"

        if [ -z "$KEYS" ]; then
            KEY="$PAIR_KEY"
        else
            KEY="$KEYS:$PAIR_KEY"
        fi

        if jq -e . >/dev/null 2>&1 <<< "$PAIR_VALUE"; then
            get_settings "$PAIR_VALUE" "$KEY"
        else
            SETTINGS["$KEY"]="$PAIR_VALUE"
        fi
    done <<< "$JSON"
}

打电话给它:

get_settings "$SETTINGS_JSON"

将像这样访问该数组:

${SETTINGS[grandparent:parent:child]}

0
投票

要有效地将JSON对象加载到bash关联数组中(不使用bash中的循环),可以使用工具'jq',如下所示。

# first, load the json text into a variable:
json='{"SALUTATION": "Hello world", "SOMETHING": "bla bla bla Mr. Freeman"}'

# then, prepare associative array, I use 'aa':
unset aa
declare -A aa

# use jq to produce text defining name:value pairs in the bash format
# using @sh to properly escape the values
aacontent=$(jq -r '. | to_entries | .[] | "[\"" + .key + "\"]=" + (.value | @sh)' <<< "$json")

# string containing whole definition of aa in bash
aadef="aa=($aacontent)"

# load the definition (because values may contain LF characters, aadef must be in double quotes)
eval "$aadef"

# now we can access the values like this: echo "${aa[SOMETHING]}"

警告:这使用eval,如果json输入来自未知来源(可能包含eval可能执行的恶意shell命令),这是危险的。

© www.soinside.com 2019 - 2024. All rights reserved.