Matt
Matt

Reputation: 9433

How to copy a key into an object using `jq`?

My input JSON looks like this:

{
  "2018-05-15T22:00:00Z": {
    "foo": "0.0",
    "bar": "90.0"
  },
  "2018-05-15T22:30:00Z": {
    "foo": "0.0",
    "bar": "70.0"
  }
}

And I'd like to copy the key (i.e. the datetime) into the object itself to end up with:

{
  "2018-05-15T22:00:00Z": {
    "date": "2018-05-15T22:00:00Z",
    "foo": "0.0",
    "bar": "90.0"
  },
  "2018-05-15T22:30:00Z": {
    "date": "2018-05-15T22:30:00Z",
    "foo": "0.0",
    "bar": "70.0"
  }
}

I'll then collapse the outer object to be an array (using map(.)) so that the final outcome is that the date has been moved into each of the objects.

Upvotes: 1

Views: 1293

Answers (2)

peak
peak

Reputation: 116670

Slightly more economically:

with_entries(.value = ({date: .key} + .value))

This emits the object as per the Q.

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295278

One approach is to use to_entries to split your item into a key/value pair, after which each piece can be referred to directly.

$ jq '[to_entries[] | .key as $time | .value | .["time"]=$time]' <<<"$in"
[
  {
    "foo": "0.0",
    "bar": "90.0",
    "time": "2018-05-15T22:00:00Z"
  },
  {
    "foo": "0.0",
    "bar": "70.0",
    "time": "2018-05-15T22:30:00Z"
  }
]

Upvotes: 1

Related Questions