0

新手 jq 用户在这里,尝试使用 jq 过滤嵌套的 json。

{
  "data": {
    "products": [
      {
        "id": "1",
        "title": "item01",
        "description": "item01 description",
        "skus": [
          {
            "color": "blue",
            "precision": 2,
            "details": {
              "longDescription": "This a long description with a keywordA"
            }
          },
          {
            "color": "green",
            "precision": 1,
            "details": {
              "longDescription": ""
            }
          }
        ]
      },
      {
        "id": "2",
        "title": "item02",
        "description": "item02 description",
        "skus": [
          {
            "color": "red",
            "precision": 2,
            "details": {
              "longDescription": ""
            }
          },
          {
            "color": "yellow",
            "precision": 1,
            "details": {
              "longDescription": ""
            }
          }
        ]
      }
    ]
  }
}

期望的输出:

{
  "title": "item01",
  "color": "blue",
  "longDescription": "This a long description with a keywordA"
}

我能够得到标题和描述jq '.data.products[] | {title: .title, longDescription: .skus[].details.longDescription } | select(.longDescription | contains("keywordA") )' 结果:

{
  "title": "item01",
  "longDescription": "This a long description with a keywordA"
}

但是,如果我在过滤器中包含颜色,我会得到不准确的数据。 jq '.data.products[] | {title: .title, color:.skus[].color, longDescription: .skus[].details.longDescription } | select(.longDescription | contains("keywordA") )'

{
  "title": "item01",
  "color": "blue",
  "longDescription": "This a long description with a keywordA"
}
{
  "title": "item01",
  "color": "green",
  "longDescription": "This a long description with a keywordA"
}
4

1 回答 1

1

有很多可能性,但以下使用“生成和测试”方法的过滤器确实产生了所需的结果并说明了一些可能的技术:

.data.products[]
| {title} + (.skus[] | {color} + (.details | {longDescription}))
| select(.longDescription | contains("keywordA"))
于 2018-06-22T01:24:01.693 回答