【问题标题】:jq variable seems to hid original inputjq 变量似乎隐藏了原始输入
【发布时间】:2020-02-20 20:12:10
【问题描述】:

我正在尝试解析一些 json 并将某些部分放入变量中。不过,我想我不了解变量的工作原理。

json:

{
  "resources": [
    {
      "type": "Microsoft.ApiManagement/service/apis"
    },
    {
      "type": "Microsoft.ApiManagement/service/apis/schemas"
    }
  ]
}

然后使用这个jq:

.resources[] | select(.type == "Microsoft.ApiManagement/service/apis") as $apis | { types: [.type], apis: $apis}

我明白了:

{
  "types": [
    "Microsoft.ApiManagement/service/apis"
  ],
  "apis": {
    "type": "Microsoft.ApiManagement/service/apis"
  }
}

当我预料到这一点时:

{
  "types": [
    "Microsoft.ApiManagement/service/apis",
    "Microsoft.ApiManagement/service/apis/schemas"
  ],
  "apis": {
    "type": "Microsoft.ApiManagement/service/apis"
  }
}

https://jqplay.org/s/4aeBOY9x6q

根据jq manual的变量部分

表达式 exp 为 $x | ... 表示:对于表达式的每个值 exp,使用整个原始输入运行管道的其余部分,以及 将 $x 设置为该值。因此,作为某种 foreach 的功能 循环。

这让我认为 .type 应该从原始集合返回,而不是我存储在 $apis 中的过滤结果。断开连接在哪里?

【问题讨论】:

    标签: json variables jq


    【解决方案1】:

    select“隐藏”了一些输入。

    要产生您期望的输出,最简单的方法是根本不使用变量。例如,您可以简单地写:

    .resources[].type
    

    【讨论】:

    • 稍后的目标是从 json 中的不同区域构建结果,因此我将收集如下变量:select(.type == "Microsoft.ApiManagement/service/apis") as $apis select(.type == "Microsoft.ApiManagement/service/apis/schemas") as $schemas select(.type == "Microsoft.ApiManagement/service/apis/operations/tags") as $operationTags 然后在最后我希望用 {$apis, $schemas}...etc 中的变量构建一个对象
    • 我建议按照minimal reproducible example 指南提出一个新的 SO 问题。
    猜你喜欢
    • 2011-01-17
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多