0

An API returns a JSON array like this:

[
  {
    "name": "Rangsdorf, Bahnhof",
    "lat": 52.294125,
    "lon": 13.431112
  },
  {
    "name": "Leipzig, Hauptbahnhof",
    "lat": 51.344817,
    "lon": 12.381321
  },
  {
    "name": "Senftenberg, Bahnhof",
    "lat": 51.52679,
    "lon": 14.003977
  },
 [...]
]

I'd like to retrieve that (or one) dict out of the array with the most northern position (i. e. where lat has a maximum) using jq. In the example, I'd expect either

{
  "name": "Rangsdorf, Bahnhof"
}

or, even better

  {
    "name": "Rangsdorf, Bahnhof",
    "lat": 52.294125,
    "lon": 13.431112
  }

as a result using jq.

2
  • 1
    easy solution with jq: <file.json jq 'max_by(.lat)', or also an easy and invariant solution with jtc: <file.json jtc -w'[lat]:<>G[-1]'
    – Dmitry
    Feb 23, 2020 at 15:34
  • Ok, thanks, that looks easy. Could you please i) briefly explain how this works and ii) post it as an answer? Feb 25, 2020 at 10:08

1 Answer 1

1

So jq 'max_by(.lat)' input.json

max_by is a function that will scan a array and return the element that is the greater .

The type can be a string or a number .

You have more examples in the documentation https://stedolan.github.io/jq/manual/v1.5/#Builtinoperatorsandfunctions

some examples :

we have array of objects , we use a the property p

echo '[{"n":"a","p":1},{"n":"c","p":2},{"n":"b","p":8}]'| jq 'max_by(.p)'
{
  "n": "b",
  "p": 8
}

we have array of objects , we use a the property n

echo '[{"n":"a","p":1},{"n":"c","p":2},{"n":"b","p":8}]'| jq 'max_by(.n)'
{
  "n": "c",
  "p": 2
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.