shell jq with json Cannot index string with string“version”

ruoxqz4g  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(153)

示例Json

{
  "product": [
    {
      "versions": "1.0",
      "components": [
        {
          "name": "JVM",
          "version": "11.0.16"
        },
        {
          "name": "TOMCAT",
          "version": "9.0.56"
        }
      ]
    },
    {
      "versions": "1.1",
      "components": [
        {
          "name": "JVM",
          "version": "11.0.16"
        },
        {
          "name": "TOMCAT",
          "version": "9.0.56"
        }
      ]
    }
  ]
}

命令

jq -r '.product[] | .versions, .components[] | "\(.name): \(.version)"' version_mapper.json

输出

jq: error (at version_mapper.json:29): Cannot index string with string "version"

错误命令

jq -r '.product[] | .wrongKey, .components[] | "\(.name): \(.version)"' version_mapper.json

输出

null: null
JVM: 11.0.16
TOMCAT: 9.0.56
null: null
JVM: 11.0.16
TOMCAT: 9.0.56

不知道发生了什么

llew8vvj

llew8vvj1#

如果你想要每个组件nameversion,就不需要.versions,这就足够了:

.product[].components[] | "\(.name): \(.version)"

输出

JVM: 11.0.16
TOMCAT: 9.0.56
JVM: 11.0.16
TOMCAT: 9.0.56

如果要包含产品本身的versions,可以在显示.versions后循环遍历组件,例如以下筛选器

.product[] | .versions, (.components[] | "\t\(.name): \(.version)")

输出

1.0
    JVM: 11.0.16
    TOMCAT: 9.0.56
1.1
    JVM: 11.0.16
    TOMCAT: 9.0.56

如果你不需要字符串插值,"\(.name): \(.version)"可以替换为join(": "),例如:

.product[].components[] | join(": ")

相关问题