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

查看:100
本文介绍了将使用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,.....]

我使用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天全站免登陆