user1877106
user1877106

Reputation: 67

JQ: print dictionary key names in correct order together with enclosed attributes

I'm trying to use jq to extract the toplevel Attribute names together with the enclosed timestamps.

json input:

[
  {
    "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"
      }
    }
  }
]

desired output:

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

Tried jq '.[] | keys' which gives me only the toplevel dictionary names.

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

Which filter would achieve this?

Upvotes: 0

Views: 400

Answers (1)

jq170727
jq170727

Reputation: 14715

Here is a filter which uses map_values to produce the specified output:

map( map_values(._metadata.timestamp) )

Sample Run (assuming data in 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!

Upvotes: 1

Related Questions