简体   繁体   English

BASH和jq访问JSON键值对

[英]BASH and jq to access JSON key-value pair

How can I access the key and value in BASH and/or jq?如何访问 BASH 和/或 jq 中的键和值?

I have a command shown below:我有一个如下所示的命令:

asg_name="bleh"
aws autoscaling describe-auto-scaling-groups \
    --auto-scaling-group-names $asg_name | 
    jq -r '.AutoScalingGroups[].Instances[] | 
           {InstanceId: .InstanceId, HealthStatus: .HealthStatus, LifecycleState: .LifecycleState}'

which produces the following format:产生以下格式:

{
  "InstanceId": "i-jibberish",
  "HealthStatus": "Healthy",
  "LifecycleState": "InService"
}
{
  "InstanceId": "i-jibberish",
  "HealthStatus": "Healthy",
  "LifecycleState": "InService"
}

How can I extract the value of each key in each JSON block (as the same row) so that I can use it in another process?如何提取每个 JSON 块(作为同一行)中每个键的值,以便我可以在另一个进程中使用它? Similar to the following effect:类似如下效果:

for obj in $results
do
   if [ obj[ValueOfHealthStatus] = "Healthy" ] && [ obj[ValueLifeCycleState] = "InService" ]; then
      do_something(obj[ValueOfInstanceId])   
   fi
done

Is it possible at all?有可能吗?

Thanks谢谢

Implemented as Bash logic:实现为 Bash 逻辑:

#!/usr/bin/env bash

jq -s -j '.[]|(.InstanceId + "\u001f" + .HealthStatus + "\u001f" + .LifecycleState, "\u0000")' a.json |
while IFS=$'\37' read -r -d '' InstanceId HealthStatus LifecycleState; do
  if [ "$HealthStatus" == 'Healthy' ] && [ "$LifecycleState" == 'InService' ]; then
    echo do_something "$InstanceId"
  fi
done

Implemented as jq logic:实现为jq逻辑:

#!/usr/bin/env bash

jq -sj '.[]|if .HealthStatus=="Healthy" and .LifecycleState=="InService" then .InstanceId + "\u0000" else empty end' a.json |
while IFS= read -r -d '' InstanceID; do
  echo do_something "$InstanceID"
done

EDIT Forgot about jq select which is even more appropriate here than an if then else empty end :编辑忘记了jq select在这里比if then else empty end更合适:

#!/usr/bin/env bash

jq -sj '.[] | select(.HealthStatus == "Healthy" and .LifecycleState == "InService") | .InstanceId + "\u0000"' a.json |
while IFS= read -r -d '' InstanceID; do
  echo do_something "$InstanceID"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM