使用jq将对象的嵌套JSON转换为bash数组的数组 [英] Convert a nested JSON of objects into array into a bash array using jq
问题描述
我在做一些根本上错误的事情,但看不到是什么,有人可以在这里指出我的jq或JSON错误吗?
I am doing something fundamentally wrong but just can't see what, could some kind person point out my fault with jq or JSON here?
我在数组"entries
"中包含以下子对象
I have the the following child objects contained within an array "entries
"
{
"profile": {
"name": "TesterRun1",
"download": {
"entries": [{
"ENTRY_A": "testserver1_place_com",
"store": "A",
"type": "direct"
},
{
"ENTRY_B": "testserver2_anotherplace_com",
"store": "B",
"type": "bypass"
},
{
"ENTRY_B": "testserver2_anotherplace_com",
"store": "A",
"type": "bypass"
}
]
}
}
}
我希望使用下面的查询将它们转换为可以通过jq函数"to_entries
"通过bash访问的数组,但到目前为止没有任何内容!
I wish to convert these to an array accessible by bash via the jq function "to_entries
" using the below query but so far nothing!
jq 'to_entries|.[]|.profile.download.entries|select(.store=="A")|.[]'
您可以在此处看到JQ Play上没有任何内容-在此处输入链接描述
You can see here that nothing is returned on JQ Play - enter link description here
请帮助保存我的理智,我在做什么错
Please help save my sanity, what am I doing wrong
推荐答案
to_entries
与将JQ结果暴露给bash无关.而是,它接受JSON对象中的每个条目并发出{"key": key, "value": value}
对.
to_entries
has nothing whatsoever to do with exposing JQ results to bash. Rather, it takes each entry in a JSON object and emits a {"key": key, "value": value}
pair.
如果您要标识和提取任意键,那么 很有用.例如:
That can be useful, if you want to identify and extract arbitrary keys. For example:
#!/usr/bin/env bash
jq_script='
.profile.download.entries[]
| select(.store == "A")
| to_entries[]
| select(.key != "store")
| select(.key != "type")
| [.key, .value]
| @tsv
'
declare -A array=( )
while IFS=$'\t' read -r key value; do
array[$key]=$value
done < <(jq -r "$jq_script")
# print array output
declare -p array
...如果在stdin上提供了输入,则将发出(尽管仅一行,而空白没有更改):
...will, when given your input on stdin, emit (albeit on a single line, without the whitespace changes):
declare -A array=([ENTRY_A]="testserver1_place_com"
[ENTRY_B]="testserver2_anotherplace_com" )
...我假设 是因为您实际上想要的是这个问题,因为在这个问题上没有任何更好的描述.
...which I assume, for lack of any better description in the question, is what you actually want.
这篇关于使用jq将对象的嵌套JSON转换为bash数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!