本文介绍了使用jq遍历JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JSON对象数组的样子:

This is what my JSON array of objects looks like:

[
    {
        "Description": "Description 1",
        "OutputKey": "OutputKey 1",
        "OutputValue": "OutputValue 1"
    },
    {
        "Description": "Description 2",
        "OutputKey": "OutputKey 2",
        "OutputValue": "OutputValue 2"
    },
    {
        "Description": "Description 3",
        "OutputKey": "OutputKey 3",
        "OutputValue": "OutputValue 3"
    },
    {
        "Description": "Description 4",
        "OutputKey": "OutputKey 4",
        "OutputValue": "OutputValue 4"
    },
    {
        "Description": "Description 5",
        "OutputKey": "OutputKey 5",
        "OutputValue": "OutputValue 5"
    },
    {
        "Description": "Description 6",
        "OutputKey": "OutputKey 6",
        "OutputValue": "OutputValue 6"
    }
]

如何使用jq对此进行迭代,以便可以在其他命令中使用OutputKey和OutputValue的值?

How do i iterate over this using jq so that i can use the values of OutputKey and OutputValue in other commands?

推荐答案

假定您的内容来自in.json:

#!/usr/bin/env bash
case $BASH_VERSION in (""|[123].*) echo "Bash 4.0 or newer required" >&2; exit 1;; esac

declare -A values=( ) descriptions=( )

while IFS= read -r description &&
      IFS= read -r key &&
      IFS= read -r value; do
  values[$key]=$value
  descriptions[$key]=$description
  echo "Read key $key, with value $value and description $description" >&2
done < <(jq -r '.[] | (.Description, .OutputKey, .OutputValue)' <in.json)

给出您的输入,这将向stderr发出以下消息:

Given your input, this emits the following to stderr:

Read key OutputKey 1, with value OutputValue 1 and description Description 1
Read key OutputKey 2, with value OutputValue 2 and description Description 2
Read key OutputKey 3, with value OutputValue 3 and description Description 3
Read key OutputKey 4, with value OutputValue 4 and description Description 4
Read key OutputKey 5, with value OutputValue 5 and description Description 5
Read key OutputKey 6, with value OutputValue 6 and description Description 6

此外,运行此代码后,您可以然后执行:

Moreover, after this code is run, you can then execute:

key_to_look_up="OutputKey 1"
echo "${values[$key_to_look_up]}"
echo "${descriptions[$key_to_look_up]}"

...并获得输出:

OutputValue 1
Description 1

这篇关于使用jq遍历JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:58