如何从 JSON 哈希构造关联 Bash 数组?
How to construct associative Bash array from JSON hash?
题目正好与相反。鉴于以下 JSON:
{
"a": "z",
"b": "y",
"c": "x"
}
我想要一个关联的 Bash 数组。
你可以这样做:
while IFS=':' read k v
do
dict[$k]="$v"
done <<< "$( sed -E "s/(\"|,|{|})//g; /^ *$/d; s/^ *//g" input.txt )"
echo "The value of key 'a' is : ${dict[a]}"
希望对您有所帮助!
以 NUL 分隔的流是最安全的方法:
input='{"a":"z","b":"y","c":"x"}'
declare -A data=()
while IFS= read -r -d '' key && IFS= read -r -d '' value; do
data[$key]=$value
done < <(jq -j 'to_entries[] | (.key, "\u0000", .value, "\u0000")' <<<"$input")
注意 jq -j
的使用,它禁止引用(如 -r
),但 也 禁止项目之间的隐式换行符,让我们手动插入取而代之的是 NUL。
请参阅 https://github.com/stedolan/jq/issues/1271 中的讨论(一张明确要求以 NUL 分隔的输出模式的票证),其中首次提出了这个习语。
题目正好与
{
"a": "z",
"b": "y",
"c": "x"
}
我想要一个关联的 Bash 数组。
你可以这样做:
while IFS=':' read k v
do
dict[$k]="$v"
done <<< "$( sed -E "s/(\"|,|{|})//g; /^ *$/d; s/^ *//g" input.txt )"
echo "The value of key 'a' is : ${dict[a]}"
希望对您有所帮助!
以 NUL 分隔的流是最安全的方法:
input='{"a":"z","b":"y","c":"x"}'
declare -A data=()
while IFS= read -r -d '' key && IFS= read -r -d '' value; do
data[$key]=$value
done < <(jq -j 'to_entries[] | (.key, "\u0000", .value, "\u0000")' <<<"$input")
注意 jq -j
的使用,它禁止引用(如 -r
),但 也 禁止项目之间的隐式换行符,让我们手动插入取而代之的是 NUL。
请参阅 https://github.com/stedolan/jq/issues/1271 中的讨论(一张明确要求以 NUL 分隔的输出模式的票证),其中首次提出了这个习语。