Leave only fields with string values

南笙酒味 提交于 2021-01-20 06:50:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!