script'n'code
script'n'code

Reputation: 365

Cant manage to extract a field using JQ in a json file

I've been searching for a solution on this forever but still haven't managed to do it.

I'm trying to get the long number field (see below) and ommit everything else but fail to do so.

This is the JSON file contents:

{
    "jsonProfile": {
        "version": "1.0",
        "format": 1
    },
    "authenticationDatabase": {
        "JQ_Newb": {
            "username": "JQ_Newb",
            "profiles": {
                "12345678901234567890123456789012": {
                    "displayName": "JQ_Newb"
                }
            }
        }
    }
}

This is my filter:

.authenticationDatabase|.[]|.profiles

And this is the result:

{
  "12345678901234567890123456789012": {
    "displayName": "JQ_Newb"
  }
}

Thanks for helping, Stackoverflow people!

Upvotes: 1

Views: 376

Answers (2)

J. Doe
J. Doe

Reputation: 1597

I had answered you but you were no longer in the channel - it's not very active as you may have noticed ;_;

You've already been given a working solution but here was my answer using keys

user@host $ jq -r '.authenticationDatabase.JQ_Newb.profiles | keys' jqnewb.json 
[
  "12345678901234567890123456789012"
]
user@host $ jq -r '.authenticationDatabase.JQ_Newb.profiles | keys[]' jqnewb.json 
12345678901234567890123456789012

Upvotes: 1

Bertrand Martel
Bertrand Martel

Reputation: 45473

The following will extract all key names from .authenticationDatabase.JQ_Newb.profiles :

jq -r '.authenticationDatabase.JQ_Newb.profiles | to_entries[] | .key' data.json

In case you have multiple keys in .authenticationDatabase.JQ_Newb.profiles, it will give :

12345678901234567890123456789012
12345678901234567890123456789013

To get the values under all keys in .authenticationDatabase.JQ_Newb.profiles :

jq -r '.authenticationDatabase.JQ_Newb.profiles | to_entries[] | .value ' data.json

Upvotes: 1

Related Questions