Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use `jq` to obtain the keys

Tags:

My json looks like this :

{   "20160522201409-jobsv1-1": {     "vmStateDisplayName": "Ready",     "servers": {       "20160522201409 jobs_v1 1": {         "serverStateDisplayName": "Ready",         "creationDate": "2016-05-22T20:14:22.000+0000",         "state": "READY",         "provisionStatus": "PENDING",         "serverRole": "ROLE",         "serverType": "SERVER",         "serverName": "20160522201409 jobs_v1 1",         "serverId": 2902       }     },     "isAdminNode": true,     "creationDate": "2016-05-22T20:14:23.000+0000",     "totalStorage": 15360,     "shapeId": "ot1",     "state": "READY",     "vmId": 4353,     "hostName": "20160522201409-jobsv1-1",     "label": "20160522201409 jobs_v1 ADMIN_SERVER 1",     "ipAddress": "10.252.159.39",     "publicIpAddress": "10.252.159.39",     "usageType": "ADMIN_SERVER",     "role": "ADMIN_SERVER",     "componentType": "jobs_v1"   } } 

My key keeps changing from time to time. So for example 20160522201409-jobsv1-1 may be something else tomorrow. Also I may more than one such entry in the json payload.

I want to echo $KEYS and I am trying to do it using jq.

Things I have tried : | jq .KEYS is the command i use frequently.

Is there a jq command to display all the primary keys in the json?

I only care about the hostname field. And I would like to extract that out. I know how to do it using grep but it is NOT a clean approach.

like image 328
sudhishkr Avatar asked Jun 01 '16 19:06

sudhishkr


People also ask

What is the use of jq command?

The JQ command is used to transform JSON data into a more readable format and print it to the standard output on Linux. The JQ command is built around filters which are used to find and print only the required data from a JSON file.

What is jq query?

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

You can simply use: keys:

% jq 'keys' my.json [   "20160522201409-jobsv1-1" ] 

And to get the first:

% jq -r 'keys[0]' my.json 20160522201409-jobsv1-1 

-r is for raw output:

--raw-output / -r: With this option, if the filter’s result is a string then it will be written directly to standard output rather than being formatted as a JSON string with quotes. This can be useful for making jq filters talk to non-JSON-based systems.

Source

If you want a known value below an unknown property, eg xxx.hostName:

% jq -r '.[].hostName' my.json 20160522201409-jobsv1-1 
like image 151
Andreas Louv Avatar answered Sep 24 '22 13:09

Andreas Louv