2016-09-28 83 views
2

这是我的对象的JSON数组看起来像JSON对象:遍历使用JQ

[ 
    { 
     "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的价值?

+0

@tripleee,作为其他问题接受答案的作者,我选择了单独回答这个问题,因为重读这个问题的答案,我不认为这是在这里特别有用/适用 - 它花费了太多的时间在“杂草”中,OP做错了什么,还没有提供一个普遍适用的良好实践。事实上,它假设OP已经知道jq,并且严格地关注bash的结束 - 并没有提供关于如何实际遍历数组的指导。 –

+0

@tripleee,......老实说,如果有空间把另一个作为另一个的副本来关闭,我几乎会试图关闭这个作为这个的副本,因为这里的答案更可能对其他人有用(并且这里的问题以一种有利于这种答案的方式被询问,而没有需要一系列指导/修正的事先实施)。 –

+0

@tripleee,...我已经更新了另一个问题,以更好地反映它的(不是特别可概括的)内容的标题。 –

回答

6

假设您的内容是从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) 

鉴于你的输入,它会产生以下标准错误:

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 

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

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

...并获得尽可能输出:

OutputValue 1 
Description 1 
+1

请注意'。[] | [.Description,.OutputKey,.OutputValue] | 。[]'可以简化为:'。[] | (.Description,.OutputKey,.OutputValue)',甚至可以在这个特殊情况下删除这些parens。 – peak

+0

好点,谢谢!我认为这些parens增加了清晰度,所以我会保留它们,但是你实际上帮助我更好地理解了jq的模型。 –

+0

(摆脱不必要的中间数组在每个方面都有所改进 - 更具可读性,处理开销更少;再次感谢您)。 –

1
  1. 恐怕你的问题不是很清楚。如果您想通过除jq之外的某个工具或应用程序来生成消费的值,那么知道该工具期望的内容会很有帮助。如果你想使用jq本身的值,那么你可以使用mapreduce;或者,可以使用具有以下形式的过滤器:.[] | ...[.[] ...],其中...是访问感兴趣值的一些jq代码,例如,

    [.[] | [.OutputKey, .OutputValue] ] 
    
  2. 如果要执行一些归约操作,那么你可能会想使用形式:reduce .[] as $x (_; _)

  3. 还有其他的选择,这取决于它是什么你正在尝试做的。

+0

我修复了JSON。我试图在这个数组上运行一个for循环,并获取我可以传递给我在for循环中调用的其他函数的值。我期望得到的值是使用OutputKey。 – Asdfg