如何用jq将json文档中的空值替换为特定值? [英] How can I replace a null value in a json document by a specific value with jq?

查看:165
本文介绍了如何用jq将json文档中的空值替换为特定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件,其中包含null作为某些键的值,我想用某些特定值替换.

I have a json file that contains nulls as values for some keys, which I would like to replace with some specific value.

输入以下内容:

{
  "id": null,
  "rows": [
    {
      "panels": [
        {
          "title": "Panel1",
          "datasource": null
        },
        {
          "title": "Panel2",
          "datasource": null
        }
      ]
    }
  ]
}

我想拥有

{
  "id": null,
  "rows": [
    {
      "panels": [
        {
          "title": "Panel1",
          "datasource": "mydb"
        },
        {
          "title": "Panel2",
          "datasource": "mydb"
        }
        ]
     }
  ]
}

我目前使用的是

sed 's/"datasource": null/"datasource": "mydb"/'

这会产生我需要的输出,但是我一直认为,当像jq这样的工具可以更好地在JSON上工作时,使用sed来完成这项工作是很可惜的.

This produces the output I need, but I keep thinking that it is a shame to use sed for this job, when there are tools like jq that can work on JSON in a much better way.

推荐答案

首先,您需要确定要更新的对象.由于要将面板的空数据源设置为"mydb",因此可以执行以下操作:

First you need to identify the objects you want to update. Since you want to set the null datasources of the panels to "mydb", you could do this:

$ jq '.rows[].panels[].datasource //= "mydb"' input.json

如果要在任何级别上更新任何对象上的任何datasource属性,则可以使用..递归搜索它们.

If you want to update any datasource property on any object at any level, you could use .. to recursively search for them.

$ jq '(.. | select(objects | has("datasource"))).datasource //= "mydb"' input.json

这篇关于如何用jq将json文档中的空值替换为特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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