How to manage empty select results

雨燕双飞 提交于 2020-02-06 13:07:22

问题


I have this input JSON

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Amsterdam",
               "short_name" : "Amsterdam",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Government of Amsterdam",
               "short_name" : "Government of Amsterdam",
               "types" : [ "administrative_area_level_2", "political" ]
            }
         ]
      }
   ]
}

If I apply this filter with jq

.results[0]|{label:"a",test:(.address_components[].types|select(.[0]| contains("administrative_area_level_2"))|.[1]?)}

I have a result

{
  "label": "a",
  "test": "political"
}

If I modify the filter in (it's an empty selection)

.results[0]|{label:"a",test:(.address_components[].types|select(.[0]| contains("administrative_area_level_3"))|.[1]?)}

I have a completely empty result.

How to obtain something like

{
  "label": "a",
  "test": ""
}

How to manage it with jq?


回答1:


You can use the alternative operator //. The expression E // "" will produce the empty string if E is empty or null or false:

<file jq '.results[0]|{label:"a",test:((.address_components[].types|select(.[0]| contains("administrative_area_level_3"))|.[1])//"")}'

Notice that in the present case you don't need the ? operator.




回答2:


if you're not limited to the jq, may I kindly offer you an alternative tool I recently developed - jtc, with that tool your ask would look like (assuming your json is in file.json):

bash $ echo '{ "label": "a", "test": "" }' | jtc -w'<test>l' -eu jtc -w'<administrative_area_level_2> [-1] [1]' file.json \;  
{
   "label": "a",
   "test": "political"
}
bash $ echo '{ "label": "a", "test": "" }' | jtc -w'<test>l' -eu jtc -w'<administrative_area_level_3> [-1] [1]' file.json \;  
{
   "label": "a",
   "test": ""
}
bash $ 

UPDATE: starting from jtc v.167, the cli argument (of -eu) requires additional quoting, e.g.:

bash $ echo '{ "label": "a", "test": "" }' | jtc -w'<test>l' -eu jtc -w"'<administrative_area_level_2> [-1] [1]'" file.json \;
{
   "label": "a",
   "test": "political"
}
bash $ 

PS. you may find jtc on github.com, or google up with keywords jtc and json



来源:https://stackoverflow.com/questions/54361098/how-to-manage-empty-select-results

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