Print the first value without knowing the key

Viewed 1066

I have a JSON value

{
    "RandomKey1": "3.1.44.0",
    "Common": {
        "Services": "3.50.103.0",
        "Common": "3.50.103.0"
    }
}

I want to get the value of RandomKey1. As you may have guessed, the name of the key changes every time when I load the page, so I need to get the value of the 0th key. It is guaranteed to be at the 0th position

I was expecting at least some result with this

cat result.json | jq -r '.[0]'

but instead I get the error

jq: error (at <stdin>:0): Cannot index object with number. 

I tried the function keys and it is returning the keys as expected. However there is no values function otherwise I could have obtained the values and return only the first element

cat result.json | jq -r 'keys'

Is there any way to get the 0th value from this string when the key name is unknown ?

3 Answers

You're looking for first/1.

first(.[])

Online demo

If you at least know that the first value is always scalar, then you can discard the rest of the input to avoid exhausting memory and wasting CPU time.

$ jq --stream -n 'input[1]' file
"3.1.44.0"

I tried the function keys

You could use the keys_unsorted function like so:

.[keys_unsorted[0]]

You can use the to_entries function to get there!

jq 'to_entries|.[0].value' file.json

should do the trick.

From jq doc:

If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

So after it your json will look like this:

[
  {
    "key": "RandomKey1",
    "value": "3.1.44.0"
  },
  {
    "key": "Common",
    "value": {
      "Services": "3.50.103.0",
      "Common": "3.50.103.0"
    }
  }
]

where you can find the first key and its corresponding value.

Related