Leave only fields with string values

Viewed 84

I have a JSON structure like this:

{
  "1": "a-secret",
  "A": "b-secret",
  "2": {
    "3": "ab-secret",
    "4": {
      "5": "adc-secret"
    },
    "6": {
      "7": "abdc-secret"
    }
  }
}

I am trying to create a command (preferable one liner) to return key pairs that only have string values. So for the above it would return:

{
  "1": "a-secret",
  "A": "b-secret"
}

I have found .[]|strings that returns only the string values but I need both the key and value and that's where I'm stumped!

2 Answers

You are looking for map_values.

$ jq 'map_values(strings)' file
{
  "1": "a-secret",
  "A": "b-secret"
}

As an alternate solution, especially on versions prior to jq-1.6 you could use with_entries to filter on values whose type is string

with_entries(select(.value | type == "string"))
Related