json - JQ 仅在字段存在时才创建字段

在 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/

相关文章:

javascript - 谷歌登录 : disable autologin on page load

sql - 如何将某个 SQL 列移动到表中的不同位置?

.net - 如何配置 NHibernate 以使用 MS SQL 2016 (RTM)?

google-maps - 如何在 angular2 中显示带有地址的谷歌地图

ajax - perl 中是否允许使用单个元素列表?

python-3.x - python : How to call a variable in an

reactjs - 警告 : Unexpected key "A" found in previou

html - Bootstrap 导航栏品牌链接不起作用

ipython-notebook - jupyter:没有可用的内核

javascript - 如何在 v-for 中访问对象属性名称