在 jq 中,如何确保仅当 k,v 存在于被检查的对象中时才创建它?例如,假设我有一个像这样的对象:
{
"student":{
"name": "george",
"age" : "15",
"quote": "Hello I am George"
}
}
我做 cat text.txt | jq '{name: .student.name, quote: .student.quote}'
创建:
{
"name": "george",
"quote": "Hello I am George"
}
不过有些词条不完整,我不想写空的K,V。假设我得到:
{
"student":{
"name": "Shirley"
}
}
使用上面的当前 jq 这将创建:
{
"name": "Shirley",
"quote": null,
}
有没有办法告诉 jq 只创建 'quote'
键(如果它存在(即不为空))?或者更一般地说,仅当它们存在于被检查的对象中时才创建所有键。
最佳答案
这是对象添加非常方便的地方,特别是因为 $obj + null
产生 $obj
(如果 $obj
是一个 JSON对象):
.student | {name} + if has("quote") then {quote} else null end
或等同于:
def maybe(k): if has(k) then {(k): .[k]} else null end;
.student | {name} + maybe("quote")
一种略有不同的方法,具有略微不同的语义,将是:
.student | {name} + ((select(.quote) | {quote}) // null)
当然,其他变化也是可能的。
https://stackoverflow.com/questions/41823497/