1

I am trying to use jq to find the ID of a hue scene when I pass the scene name. The problem is if I update the scene it makes another scene with a new ID assigned to it. So as I make changes to the scene more than one result returns. How Do I find the newest scene? I see there is an object that is lastupdated.

Here is what I have so far:

curl -s ${BASEURL}/scenes/ | /usr/local/bin/jq -r -e --arg SCENENAME "${SCENENAME}" '. as $object | keys[] | select($object[.].name == $SCENENAME)'

Here is what the json output looks like:

  "FUX9A2m4LcuF6YG": {
    "name": "KitchenDay",
    "lights": [
      "6",
      "7",
      "10",
      "11"
    ],
    "owner": "43594f081bb6d23e9ccd254927fa47",
    "recycle": true,
    "locked": false,
    "appdata": {},
    "picture": "",
    "lastupdated": "2018-02-25T03:35:57",
    "version": 2   }
peak
  • 105,803
  • 17
  • 152
  • 177
Keo
  • 11
  • 2
  • Please show the JSON produced by the curl command, the value of SCENENAME, and the expected output. See also https://stackoverflow.com/help/mcve – peak Mar 10 '18 at 06:07
  • Sorry I just realized you asked for the value of SCENENAME. In my exmample I used KitchenDay. I want to get the key of the scene with the newest lastupdated value. Right now my code returns the key of any entry that matches name == KitchenDay. – Keo Mar 11 '18 at 02:16

1 Answers1

1

In this response, I'll assume the following input, which seems to capture the essence of the problem:

{
  "FUX9A2m4LcuF6YG": {
    "name": "KitchenDay",
    "lastupdated": "2018-02-25T03:35:57"
  },
  "later": {
    "name": "KitchenNight",
    "lastupdated": "2018-02-25T23:35:57"
  }
}

With that as input, the following filter:

to_entries | [max_by(.value.lastupdated)] | from_entries

produces:

{
  "later": {
    "name": "KitchenNight",
    "lastupdated": "2018-02-25T23:35:57"
  }
}

The key here is that the max of the "lastupdated" field corresponds to the most recent time.

If you just want the key name, you could instead write:

to_entries | max_by(.value.lastupdated) | .key
peak
  • 105,803
  • 17
  • 152
  • 177
  • So my code will look like this? `curl -s ${BASEURL}/scenes/ | /usr/local/bin/jq -r -e --arg SCENENAME "${SCENENAME}" '. as $object | keys[] | select($object[.].name == $SCENENAME) | to_entries | [max_by(.value.lastupdated)] | from_entries'` Because that returns this message. `jq: error (at :0): string ("FUX9A2m4Lc...) has no keys` That string is the ID which is also the key. Any advice? – Keo Mar 10 '18 at 05:27