DEV Community

Pavol Z. Kutaj
Pavol Z. Kutaj

Posted on

How to Use JQ to find Key based on Value

USECASE

The aim of this page is to explain how to use jq to find a key based on a value in JSON data retrieved from Consul.

Consul KV Store: Used to store key-value pairs.

JSON Data: Example JSON data retrieved from Consul.

{
  "a3e705d1-98d3-4c58-80a4-f9f9c9ec3e47": "CUSTOMER_1",
  "d4b7e8e9-1b50-4f3d-b3d9-ea6b5feca1bd": "CUSTOMER_2",
  "b21c9e36-4798-4387-ae1e-f6c678b0c14e": "CUSTOMER_3"
}
Enter fullscreen mode Exit fullscreen mode

Objective: Find the key corresponding to a specific value.

jq Command: Tool for processing JSON data.

Basic jq Command:

jq -r 'to_entries[] | select(.value == "VALUE_YOU_ARE_LOOKING_FOR") | .key' yourfile.json
Enter fullscreen mode Exit fullscreen mode

Integrating with Consul:

consul kv get global/uuid-to-customer-name | jq -r 'to_entries[] | select(.value == "VALUE_YOU_ARE_LOOKING_FOR") | .key'
Enter fullscreen mode Exit fullscreen mode

Example Value: Searching for the value "anonymized_customer".

Step-by-Step Breakdown:

  • Retrieve JSON from Consul:
consul kv get global/uuid-to-customer-name
Enter fullscreen mode Exit fullscreen mode
  • Convert JSON to Key-Value Pairs:
consul kv get customer-uuids | jq -r 'to_entries[]'
Enter fullscreen mode Exit fullscreen mode
  • Output:
{
  "key": "a3e705d1-98d3-4c58-80a4-f9f9c9ec3e47",
  "value": "CUSTOMER_1"
}
{
  "key": "d4b7e8e9-1b50-4f3d-b3d9-ea6b5feca1bd",
  "value": "CUSTOMER_2"
}
{
  "key": "b21c9e36-4798-4387-ae1e-f6c678b0c14e",
  "value": "CUSTOMER_3"
}

Enter fullscreen mode Exit fullscreen mode
  • Filter for Specific Value:
consul kv get global/uuid-to-customer-name | jq -r 'to_entries[] | select(.value == "anonymized_customer")'
Enter fullscreen mode Exit fullscreen mode
  • Output:
{
  "key": "cde71158-f1d6-4707-88e0-28d1716f2790",
  "value": "anonymized_customer"
}
Enter fullscreen mode Exit fullscreen mode
  • Extract the Key:
consul kv get global/uuid-to-customer-name | jq -r 'to_entries[] | select(.value == "anonymized_customer") | .key'
Enter fullscreen mode Exit fullscreen mode
  • Output:
cde71158-f1d6-4707-88e0-28d1716f2790
Enter fullscreen mode Exit fullscreen mode

LINKS

Top comments (0)