问题
How to check for null or empty in jq and substitute for empty string in jq transformation.
Example in below JSON, this is the JQ
JQ:
.amazon.items[] | select(.name | contains ("shoes")) as $item |
{
activeItem: .amazon.activeitem,
item : {
id : $item.id,
state : $item.state,
status : if [[ $item.status = "" or $item.status = null ]];
then 'IN PROCESS' ; else $item.status end
}
}
JSON:
{
"amazon": {
"activeitem": 2,
"items": [
{
"id": 1,
"name": "harry potter",
"state": "sold"
},
{
"id": 2,
"name": "adidas shoes",
"state": "in inventory"
},
{
"id": 3,
"name": "watch",
"state": "returned"
},{
"id": 4,
"name": "Nike shoes",
"state": "in inventory"
}
]
}
}
I want to add a default string "In Process" if the status is empty or Null.
Based on Item condition, using the query below and take the first object from the filtered results.
code
.amazon.items[] | select(.name | contains ("shoes"))
code
Expected Output:
{
"activeitem": 2,
"item": {
"id": 2,
"name": "adidas shoes",
"state": "in inventory",
"status": "IN PROCESS"
}
}
回答1:
The key here is to use |=
:
.amazon.item.status |=
if . == null or . == ""
then "IN PROCESS"
else .
end
来源:https://stackoverflow.com/questions/54332521/how-to-check-for-null-or-empty-in-jq-and-substitute-for-empty-string-in-jq-trans