Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the first and the last value of a json array/object

Tags:

json

jq

I use jq 1.5 in an windows 10 enviroment. I receive via api several information include different city arrays like that:

  {

  "cruises": [
    {

      "waypoint_cities": [
        "Palma de Mallorca",
        "Cádiz",
        "Puerto del Rosario, Fuerteventura",
        "Arrecife, Lanzarote",
        "Arrecife, Lanzarote",
        "Agadir",
        "Gibraltar",
        "Barcelona",
        "Palma de Mallorca"
      ]}]}

How can i find the first and the last entry of those arrays with jq? I tried the function min/maxby but that function only delivers the entrys with the first and last in charakter of the Alphabet.

regards Timo

like image 485
TimoC Avatar asked Aug 31 '17 10:08

TimoC


People also ask

How do I get the last JSON array?

For anyone looking to do this in JSONPath syntax, you can do this with $. seats[-1:] . If you wanted to do something like get the countryid attribute nested in the last element, it would be $. seats[-1:][countryid] .

How do you find the first value of a JSON object?

The Object. values() will return an only array of values available in an object, now we can easily get the first value from the JSON object using array 0th index.

How do you find the first object of an array?

To get first element from array, use var first = array[0]; To get Name from it, use first.Name .

What is JQ C?

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed , awk , grep and friends let you play with text. jq is written in portable C, and it has zero runtime dependencies.


1 Answers

Here is a solution using first and last

.cruises[].waypoint_cities | first, last

Output

"Palma de Mallorca"
"Palma de Mallorca"
like image 57
jq170727 Avatar answered Oct 05 '22 07:10

jq170727