如何使用stedolan / jq消除JSON中的空值?

时间:2019-07-20 08:09:11

标签: json null key jq

真正的问题要复杂一些,但是以下json格式存在问题。

命令:
echo '[{"user":"a","title":"aaa"},{"user":"b","title":null}]' | jq '.[]'

出局:

{
  "user": "a",
  "title": "aaa"
}
{
  "user": "b",
  "title": null
}

我要:

{
  "user": "a",
  "title": "aaa"
}
{
  "user": "b"
}

所以我这样做:
echo '[{"user":"a","title":"aaa"},{"user":"b","title":null}]' | jq '.[]|{user:.user, title:(.title//empty)}'

结果:

{
  "user": "a",
  "title": "aaa"
}

后面的整个对象被移除。如果您知道一些好的解决方案?

2 个答案:

答案 0 :(得分:1)

最直接的方法是简单地删除不需要的密钥,例如:通过:

map( if .title == null then del(.title) else . end)

使用walk/1

如果您要全局执行此操作(即,无论标题出现在哪里,无论对象出现在何处):

walk(if type == "object" and .title == null then del(.title) else . end)

这可以使用通用功能when/2进行一些整理:

 def when(p;q): if p? // false then q else . end;

现在我们可以简单地写:

 walk( when(.title == null; del(.title)) )

整个9码

def when(p;q): if p? // false then q else . end; 

walk( when(type=="object"; with_entries( select(.value != null ))))

答案 1 :(得分:1)

或者,使用基于unix步行路径的unix实用程序 jtc 可以实现相同的要求:

bash $ JSN='[{"user":"a","title":"aaa"},{"user":"b","title":null}]'
bash $ <<<$JSN jtc -w'[title]:<>n:' -p
[
   {
      "title": "aaa",
      "user": "a"
   },
   {
      "user": "b"
   }
]
bash $ 

这将删除所有(如果有多个)记录"title":null 如果需要删除所有null值(不仅受title限制),则要使用步行路径-w'<>n:'

PS>披露:我是jtc-用于JSON操作的shell cli工具的创建者