问题
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