json - 当键存在时循环遍历 JSON 并检索集合

标签 json bash jq

我有以下数据:

{
   "storageSummary": "testvalue",
   "audit1": {
         "auditScore": 1,
         "suspensionScore": 1,
         "password" : "value1",
         "onlineScore": 0.99743587,
         "satelliteName": "us2.storj.io:7777"
      },
   "audit2": {
         "auditScore": 1,
         "suspensionScore": 1,
         "password" : "valueX",
         "onlineScore": 0.9992917,
         "satelliteName": "saltlake.tardigrade.io:7777"
      },
   "audit3": {
         "auditScore": 1,
         "suspensionScore": 1,
         "password" : "value72",
         "onlineScore": 0.99930555,
         "satelliteName": "ap1.storj.io:7777"
      }
}

在 bash 中,我需要检查这些数据,以更新所有 auditX 对象的password。我尝试过以下方法:

jq ' .[] |select(has("auditScore")) '

但是我在第一项上收到错误:

jq: error (at <stdin>:23): Cannot check whether string has a string key
exit status 5

当我删除数据中的第一个项目 "storageSummary": "testvalue" 时,我可以循环访问我的对象(但我的数据中有一些项目没有 auditscore 键)。

最终目标是在 bash for 循环中运行此结果以更新密码(并执行更具体的任务)。

您能给我指出正确的方向吗?

最佳答案

您可以使用select(type == "object")过滤对象,或使用其等效的快捷方式objects:

.[] | select(type == "object" and has("auditScore"))
# or
.[] | objects | select(has("auditScore"))

这将返回一个对象流,其中包含一个名为 auditScore

的字段
{
  "auditScore": 1,
  "suspensionScore": 1,
  "password": "value1",
  "onlineScore": 0.99743587,
  "satelliteName": "us2.storj.io:7777"
}
{
  "auditScore": 1,
  "suspensionScore": 1,
  "password": "valueX",
  "onlineScore": 0.9992917,
  "satelliteName": "saltlake.tardigrade.io:7777"
}
{
  "auditScore": 1,
  "suspensionScore": 1,
  "password": "value72",
  "onlineScore": 0.99930555,
  "satelliteName": "ap1.storj.io:7777"
}

要基于该流设置(另一个)字段,请将 LHS 包装到括号中以保留上下文:

(.[] | select(type == "object" and has("auditScore"))).password = "X"
# or
(.[] | objects | select(has("auditScore"))).password = "X"

关于json - 当键存在时循环遍历 JSON 并检索集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76254127/

相关文章:

mysql - 测验分层数据的数据库结构?

php - select2 单击时重定向

json - 通过 jq 为每个 JSON 项运行 bash 命令

linux - jq 不使用感叹号作为输入

json - ColdFusion:如何检查JSON属性是否为null?

c# - 为什么 Json.Net 将枚举值反序列化为整数并接受为有效?

Linux:使用 cut 命令删除某些字符之前和之后的所有内容

linux - 我的 Man 脚本应该放在哪里才能正常工作?

bash - 递归使用 "echo append >> file"

json - 使用 jq 转换嵌套对象数组