J. M. Becker
J. M. Becker

Reputation: 2815

Sort an array of objects within an array by most recent timestamp, and then sort the outer array by each array's first object's timestamp, using jq

Sort an array of objects within an array by most recent timestamp, and then sort the outer array by each array's first object's timestamp, using jq.

This is an example of the JSON data, at the stage of the jq pipeline where I'm stuck.

[
  [
    {
      "created_at": "2020-09-26T14:48:46.000Z",
      "conversation_id": "1309867515456237571",
      "id": "1309867515456237571",
      "text": "example1"
    }
  ],
  [
    {
      "created_at": "2020-09-26T14:48:47.000Z",
      "conversation_id": "1309867518455156736",
      "id": "1309867518455156736",
      "text": "example2"
    },
    {
      "created_at": "2020-09-26T14:48:47.000Z",
      "conversation_id": "1309867518455156736",
      "id": "1309867517846810625",
      "text": "example3"
    },
    {
      "created_at": "2020-09-26T14:48:46.000Z",
      "conversation_id": "1309867518455156736",
      "id": "1309867516659937284",
      "text": "example4"
    }
  ],
  [
    {
      "created_at": "2020-09-26T14:48:48.000Z",
      "conversation_id": "1309867524473999364",
      "id": "1309867524473999364",
      "text": "example5"
    },
    {
      "created_at": "2020-09-26T14:48:47.000Z",
      "conversation_id": "1309867524473999364",
      "id": "1309867520468291586",
      "text": "example6"
    },
    {
      "created_at": "2020-09-26T14:48:47.000Z",
      "conversation_id": "1309867524473999364",
      "id": "1309867520153845760",
      "text": "example7"
    }
  ],
  [
    {
      "created_at": "2020-09-26T14:48:48.000Z",
      "conversation_id": "1309867524750749705",
      "id": "1309867524750749705",
      "text": "example8"
    }
  ]
]

Everything I've tried ends up with an error like this one,

jq: error (at <stdin>:8): Cannot index string with string "created_at"

Upvotes: 0

Views: 128

Answers (1)

user197693
user197693

Reputation: 2045

Maybe this?

jq '.[] |= sort_by(.created_at) | sort_by(.[].created_at)'

Upvotes: 1

Related Questions