【问题标题】:JQ: print dictionary key names in correct order together with enclosed attributesJQ:以正确的顺序打印字典键名以及包含的属性
【发布时间】:2017-10-17 16:15:03
【问题描述】:

我正在尝试使用 jq 来提取顶级属性名称以及随附的时间戳。

json 输入:

[
  {
    "Something": {
      "_metadata": {
        "timestamp": "2016-02-18T12:32:50.276Z"
      }
    }
  },
  {
    "OtherThing": {
      "_metadata": {
        "timestamp": "2016-03-18T12:32:50.276Z"
      }
    }
  },
  {
    "ThirdThing": {
      "_metadata": {
        "timestamp": "2016-04-18T12:32:50.276Z"
      }
    }
  }
]

想要的输出:

[
  {
    "Something": "2016-02-18T12:32:50.276Z"
  },
  {
    "OtherThing": "2016-03-18T12:32:50.276Z"
  },
  {
    "ThirdThing": "2016-04-18T12:32:50.276Z"
  }
]

试过jq '.[] | keys',它只给了我顶级字典名称。

[
  "Something"
]
[
  "OtherThing"
]
[
  "ThirdThing"
]

哪个过滤器可以做到这一点?

【问题讨论】:

    标签: json key jq


    【解决方案1】:

    这是一个使用map_values 产生指定输出的过滤器:

    map( map_values(._metadata.timestamp) )
    

    示例运行(假设数据在data.json

    $ jq -M 'map( map_values(._metadata.timestamp) )' data.json
    [
      {
        "Something": "2016-02-18T12:32:50.276Z"
      },
      {
        "OtherThing": "2016-03-18T12:32:50.276Z"
      },
      {
        "ThirdThing": "2016-04-18T12:32:50.276Z"
      }
    ]
    

    Try it online!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      相关资源
      最近更新 更多