将使用 jq 解析的数组分配给 Bash 脚本数组 [英] Assigning an Array Parsed With jq to Bash Script Array

查看:45
本文介绍了将使用 jq 解析的数组分配给 Bash 脚本数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样用 jq 解析了一个 json 文件:

I parsed a json file with jq like this :

# cat test.json | jq '.logs' | jq '.[]' | jq '._id' | jq -s

它返回一个这样的数组:[34,235,436,546,.....]

It returns an array like this : [34,235,436,546,.....]

使用 bash 脚本我描述了一个数组:

Using bash script i described an array :

# declare -a msgIds = ...

这个数组使用 () 而不是 [] 所以当我将上面给出的数组传递给这个数组时它不会工作.

This array uses () instead of [] so when I pass the array given above to this array it won't work.

([324,32,45..]) 这会导致问题.如果我删除 jq -s,则会形成一个只有 1 个成员的数组.

([324,32,45..]) this causes problem. If i remove the jq -s, an array forms with only 1 member in it.

有没有办法解决这个问题?

Is there a way to solve this issue?

推荐答案

我们可以通过两种方式解决这个问题.它们是:

We can solve this problem by two ways. They are:

输入字符串:

// test.json
{
    "keys": ["key1","key2","key3"]
}

方法 1:

1) 使用 jq -r(输出原始字符串,而不是 JSON 文本).

1) Use jq -r (output raw strings, not JSON texts) .

KEYS=$(jq -r '.keys' test.json)
echo $KEYS
# Output: [ "key1", "key2", "key3" ]

2) 使用 @sh(将输入字符串转换为一系列以空格分隔的字符串).它从字符串中删除方括号[]、逗号(,).

2) Use @sh (Converts input string to a series of space-separated strings). It removes square brackets[], comma(,) from the string.

KEYS=$(<test.json jq -r '.keys | @sh')
echo $KEYS
# Output: 'key1' 'key2' 'key3'

3) 使用 tr 从字符串输出中删除单引号.要删除特定字符,请使用 tr 中的 -d 选项.

3) Using tr to remove single quotes from the string output. To delete specific characters use the -d option in tr.

KEYS=$((<test.json jq -r '.keys | @sh')| tr -d \') 
echo $KEYS
# Output: key1 key2 key3

4) 我们可以通过将字符串输出放在圆括号() 中来将逗号分隔的字符串转换为数组.它也称为复合赋值,我们用一堆值声明数组.

4) We can convert the comma-separated string to the array by placing our string output in a round bracket(). It also called compound Assignment, where we declare the array with a bunch of values.

ARRAYNAME=(value1 value2  .... valueN)

#!/bin/bash
KEYS=($((<test.json jq -r '.keys | @sh') | tr -d \'\"))

echo "Array size: " ${#KEYS[@]}
echo "Array elements: "${KEYS[@]}

# Output: 
# Array size:  3
# Array elements: key1 key2 key3

方法 2:

1) 使用jq -r得到字符串输出,然后使用tr删除方括号、双引号和逗号等字符.

1) Use jq -r to get the string output, then use tr to delete characters like square brackets, double quotes and comma.

#!/bin/bash
KEYS=$(jq -r '.keys' test.json  | tr -d '[],"')
echo $KEYS

# Output: key1 key2 key3

2) 然后我们可以通过将我们的字符串输出放在圆括号()中来将逗号分隔的字符串转换为数组.

2) Then we can convert the comma-separated string to the array by placing our string output in a round bracket().

#!/bin/bash
KEYS=($(jq -r '.keys' test.json  | tr -d '[]," '))

echo "Array size: " ${#KEYS[@]}
echo "Array elements: "${KEYS[@]}

# Output:
# Array size:  3
# Array elements: key1 key2 key3

这篇关于将使用 jq 解析的数组分配给 Bash 脚本数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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