英文:
What's the easiest way to map JSON array values to a dictionary using jq?
问题
You can use the following jq command to create a key-value dictionary from the given JSON data:
cat api_fm.json | jq -r 'reduce range(0, length/2) as $i ({}; . + { (.[$i]): .[$(length/2 + $i)] }) | to_entries | map("\(.key): \(.value)")'
This command will produce the desired output:
[
"plugin: Started",
"c_docker_2: Started",
"c_docker_5: Started",
"c_docker_4: Started",
"c_docker_3: Started",
"c_docker_1: Started"
]
英文:
How can I make a key value dictionary using jq?
If I do: cat api_fm.json | jq -r "[ .[].name, .[].status ]"
I receive:
[
"plugin",
"c_docker_2",
"c_docker_5",
"c_docker_4",
"c_docker_3",
"c_docker_1",
"Started",
"Started",
"Started",
"Started",
"Started",
"Started"
]
So, I would like to map the name with the status like this:
[
"plugin: started"
...
]
答案1
得分: 0
这是一种方式:
jq 'map("\(.name): \(.status)")'
英文:
Here is one way:
jq 'map("\(.name): \(.status)")'
答案2
得分: 0
以下是您要求的内容的翻译:
$ cat api_fm.json
[
{"name":"plugin", "status":"已启动"},
{"name":"c_docker_2", "status":"已启动"},
{"name":"c_docker_5", "status":"已启动"},
{"name":"c_docker_4", "status":"已启动"},
{"name":"c_docker_3", "status":"已启动"},
{"name":"c_docker_1", "status":"已启动"}
]
然后,要创建Bash关联数组的部分:
declare -A prod
while IFS=$'\t' read -r name status; do
prod["$name"]=$status
done < <(
jq -r '.[] | [.name, .status] | @tsv' api_fm.json
)
declare -p prod
declare -A prod=([c_docker_2]="已启动" [c_docker_3]="已启动" [c_docker_1]="已启动" [c_docker_4]="已启动" [c_docker_5]="已启动" [plugin]="已启动" )
英文:
Working through the requirements in your comment. Given:
$ cat api_fm.json
[
{"name":"plugin", "status":"Started"},
{"name":"c_docker_2", "status":"Started"},
{"name":"c_docker_5", "status":"Started"},
{"name":"c_docker_4", "status":"Started"},
{"name":"c_docker_3", "status":"Started"},
{"name":"c_docker_1", "status":"Started"}
]
We can produce tab-separated name-status pairs like
$ jq -r '.[] | [.name, .status] | @tsv' api_fm.json
plugin Started
c_docker_2 Started
c_docker_5 Started
c_docker_4 Started
c_docker_3 Started
c_docker_1 Started
Then, to create the bash associative array
declare -A prod
while IFS=$'\t' read -r name status; do
prod["$name"]=$status
done < <(
jq -r '.[] | [.name, .status] | @tsv' api_fm.json
)
declare -p prod
declare -A prod=([c_docker_2]="Started" [c_docker_3]="Started" [c_docker_1]="Started" [c_docker_4]="Started" [c_docker_5]="Started" [plugin]="Started" )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论