遍历JSON,检索父值

k7fdbhmy  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(146)

这是jq : loop through json and retrieve sets when key exists的后续版本。以下是数据集:

{
   "storageSummary": 6.8624392E13,
   "audit1": {
         "auditScore": 1,
         "suspensionScore": 1,
         "onlineScore": 0.99743587,
         "satelliteName": "us2.storj.io:7777"
      },
   "audit2": {
         "auditScore": 1,
         "suspensionScore": 1,
         "onlineScore": 0.9992917,
         "satelliteName": "saltlake.tardigrade.io:7777"
      },
   "audit3": {
         "auditScore": 1,
         "suspensionScore": 1,
         "onlineScore": 0.99930555,
         "satelliteName": "ap1.storj.io:7777"
      }
}

我想通过它:当auditScore为1时,我需要存储父对象名称(如audit1)和onlineScore
现在,我有这样的东西:

DS_OBJECT=$(jq -c ' .[]|select(type == "object" and has("auditScore"))' ${DS_SRC_FILE})

for row in ${DS_OBJECT}; do
    _jq() {
     echo "${row}" | jq -r "${1}"
    }
    echo -e "Processing $(_jq '.satelliteName')..."
    echo -e "onlineScore is $(_jq '.onlineScore')
done

因此,我需要提取parent object name,而不是这段代码中的satelliteName。如何使用bash和jq实现这一点(我更倾向于避免添加Ruby或任何其他语言,如前一个主题所建议的)?

5w9g7ksd

5w9g7ksd1#

您可以使用to_entries将对象转换为键值对列表。这个列表可以很容易地过滤和转换。

to_entries[]
| select(.value.auditScore == 1)?
| [.value.onlineScore, .key]
| join(" ")

我还建议不要在每个循环迭代中启动一个新的jq进程,而是生成正确的输出并解析它:

jq -r 'to_entries[]
| select(.value.auditScore == 1)?
| [.value.onlineScore, .key]
| join(" ")' | while read onlineScore name; do
    echo -e "Processing $name..."
    echo -e "onlineScore is $onlineScore"
done

或者直接在jq中执行所有操作:

jq -r 'to_entries[]
| select(.value.auditScore == 1)?
| "Processing \(.key)...\nonlineScore is \(.value.onlineScore)"'

相关问题