0

Here is a JSON response I am receiving from a server:

{
    "GoUZm0F3r-rZ0tItdurVfPLCAfBGrnvF32": {
        "entityId": "GoUZm0F3r-rZ0tItdurVfPLCAfBGrnvF32",
        "mergePolicy": {
            "id": "02596943-2bb0-497f-815c-ffc69bf4b9c0"
        }
    }
}

The value "GoUZm0F3r-rZ0tItdurVfPLCAfBGrnvF32" always changes with new response. Is it possible I can access this value dynamically to reuse it in my next API call?

Ashish
  • 1
  • 3
    Add more information to the question on exactly what you're doing, disqualifying a perfectly good answer like the one below after the fact is very bad form and could have been avoided if you had provided more information. – pzkpfw Sep 14 '23 at 21:51

2 Answers2

3

You can extract it with jq

jq -r 'keys | .[0]'
Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • 1
    Or keys | first if you want to avoid using array indexing syntax. – Kusalananda Sep 14 '23 at 18:25
  • Sorry, I can't use jq as I am using a server side application. – Ashish Sep 14 '23 at 18:25
  • 1
    @Ashish What does that mean and how are we to know what tool you have access to? Please update your question. – Kusalananda Sep 14 '23 at 21:28
  • @Ashish please at least indicate the language your server side application is written in. (however, this may be more a computer language question than a Unix or Linux specific question) – Sotto Voce Sep 14 '23 at 21:34
  • "Sorry, I can't use jq as I am using a server side application" - in that case the only answer that can be given is "possibly". There is no information in your question to provide a better answer than that, @Ashish – Chris Davies Sep 14 '23 at 21:57
0

Using Miller (mlr), which is able to convert between several common structured formats, we can get it to read the JSON input, relabel the unfortunately labelled key into just key, flatten the data and pull out the key.entityId field's value. The output is in "NIDX" (index-numbered (toolkit style)) format which is header-less and suits this application.

$ mlr --j2n label key then flatten then cut -f key.entityId file.json
GoUZm0F3r-rZ0tItdurVfPLCAfBGrnvF32

The --j2n option is a shorthand for --ijson (input JSON) together with --onidx (output NIDX).

Approximately the same operation using jq (a very common JSON processor):

$ jq -r '.[].entityId' file.json
GoUZm0F3r-rZ0tItdurVfPLCAfBGrnvF32

In both these commands, we don't really care about the top-level key and instead go for the value of the entityId key in the inner structure. JSON documents should generally store data in values, not in keys. If they don't, it's a good sign they should have used an array instead.

Kusalananda
  • 333,661