JQ创建字段(如果存在) [英] JQ create field only if it exists

查看:105
本文介绍了JQ创建字段(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jq中,如何确保仅在被检查的对象中存在k,v时才创建它?例如,假设我有一个像这样的对象:

In jq, how do I ensure a k,v is only created if it exists in the object being inspected? For example, let's say I have an object like:

{
 "student":{
    "name": "george",
    "age" : "15",
    "quote": "Hello I am George"
    }
 }

然后我执行cat text.txt | jq '{name: .student.name, quote: .student.quote}' 创建:

And I do cat text.txt | jq '{name: .student.name, quote: .student.quote}' to create:

  {
   "name": "george",
   "quote": "Hello I am George"
   }

但是,有些条目不完整,我不想写一个空的K,V.假设我得到了:

However, some of the entries are incomplete, and I don't want to write an empty K,V. Let's say I get:

{
 "student":{
    "name": "Shirley"
  }
} 

使用上面的当前jq将创建:

With the current jq above this would create:

 {
  "name": "Shirley",
  "quote": " ",
  }

有没有一种方法可以告诉jq仅创建'quote'密钥(如果存在)(即不为null)?或更笼统地说,仅当所有键都存在于被检查的对象中时,才创建它们.

Is there a way I can tell jq to only create the 'quote' key if it exists (i.e. is not null)? Or more generally, create ALL keys only if they exist in the object being inspected.

推荐答案

添加对象非常方便,特别是因为$obj + null生成$obj(如果$obj是JSON对象):

This is where object addition comes in very handy, especially since $obj + null yields $obj (if $obj is a JSON object):

.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")

语义稍有不同的一种方法是:

A slightly different approach, with subtly different semantics, would be:

.student |  {name} + ((select(.quote) | {quote}) // null)

当然其他的变化也是可能的.

Of course other variations are possible.

这篇关于JQ创建字段(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆