【问题标题】:I have some JSON but I want to extract data based on a variable using jq我有一些 JSON,但我想使用 jq 基于变量提取数据
【发布时间】:2022-01-11 12:00:42
【问题描述】:

我有一些我想使用 jq 解析的 JSON 数据

{{
    "metadata":{
      "name":"run1",
      "uid":"b2c0ce",
      "creationTimestamp":"2021-01-01T01:01:01Z"
    },
    "spec":{
      "arguments":{}
    },
    "status":{
      "phase":"Failed",
      "startedAt":"2021-01-01T01:01:01Z",
      "finishedAt":"2021-01-01T01:01:01Z"
    }
},
{
    "metadata":{
      "name":"run2",
      "uid":"9b0af3",
      "creationTimestamp":"2021-01-01T01:01:01Z"
    },
    "spec":{
      "arguments":{}
    },
    "status":{
      "phase":"Succeeded",
      "startedAt":"2021-01-01T01:01:01Z",
      "finishedAt":"2021-01-01T01:01:01Z"}}}

我有一个脚本,用户将输入“名称”,我希望能够查找并提取他们输入的名称的元数据(如果存在)。因此,例如,如果他们输入“run7”,我希望最终输出为:

{"metadata":{
    "name":"run7",
    "uid":"b2c0ce",
    "creationTimestamp":"2021-01-01T01:01:01Z"}

或者如果可能的话只显示

"name":"run7",
"uid":"b2c0ce",
"creationTimestamp":"2021-01-01T01:01:01Z"

我得到的最接近的是:

jq -r '.[] | .[] | map({name: .name, uid: .uid, time: .creationTimestamp })'  file.json

但我不确定我现在如何只搜索某个名称。我这样做的方式是这样的:

{
    "name": "run10",
    "uid": "af7b51f",
    "time": "2021-01-01T01:01:01Z"
  },
  {
    "name": null,
    "uid": null,
    "time": null
  },
  {
    "name": null,
    "uid": null,
    "time": null
  } 

我也不希望它检查“规范”或“状态”,因为那是 null 的来源

【问题讨论】:

  • 请修正您的输入 json。无效。

标签: json parsing environment-variables jq


【解决方案1】:

假设这些输入对象在一个数组中,

.[] | select(.metadata.name == "run2") | .metadata

将选择.metadata.name === run2所在的对象。

然后它显示该对象的.metadata,因此输出变为:

{
  "name": "run2",
  "uid": "9b0af3",
  "creationTimestamp": "2021-01-01T01:01:01Z"
}

Demo

【讨论】:

  • 谢谢!这正是我所需要的。第二部分没有用| .metadata,但我只包含了jq -r .uid,这正是我一直想要的
猜你喜欢
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
相关资源
最近更新 更多