问题
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!
回答1:
You are looking for map_values.
$ jq 'map_values(strings)' file
{
"1": "a-secret",
"A": "b-secret"
}
回答2:
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"))
来源:https://stackoverflow.com/questions/65201631/leave-only-fields-with-string-values