【问题标题】:Jq to replace a word with in the jsonJq 替换 json 中的一个单词
【发布时间】:2020-01-28 15:34:16
【问题描述】:

我在下面有一个 json,我需要在数据部分中获取键“toModify”的值。并且还想将 key(toModify) 值修改为另一个值,例如:hello1234567 到 xyz。我们如何使用 jq 来做到这一点。

{
  "items": [
    {
      "source": {
        "id": "12334"        
      },
      "data": {
        "name": "test",
        "value": "test",        
        "cData": [
          {
            "key": "keOne",
            "value": "hello"
          },
          {
            "key": "toModify",
            "value": "hello1234567"
          }
        ]
      } 
    }
  ]
}

【问题讨论】:

  • 到目前为止你尝试过什么?你检查过类似的问题吗?你读过教程吗?

标签: json jq edit


【解决方案1】:

您的输入,特别是 cData 键的值,看起来是为与 to_entriesfrom_entries 一起使用而量身定制的。

$ jq '.items[0].data.cData |= (from_entries | .toModify = "xyz" | to_entries)' tmp.json
{
  "items": [
    {
      "source": {
        "id": "12334"
      },
      "data": {
        "name": "test",
        "value": "test",
        "cData": [
          {
            "key": "keOne",
            "value": "hello"
          },
          {
            "key": "toModify",
            "value": "xyz"
          }
        ]
      }
    }
  ]
}

【讨论】:

  • 警告:建议的解决方案假定键名是不同的。
  • 呃,是的,希望如此:)
  • 我尝试过使用select(.key == "toModify),但并没有真正追求它;我相信这可以让您在保留重复项的同时更改每个对象。
【解决方案2】:

要求有点粗略,但以下在这种特殊情况下产生了预期的结果,并说明了一种方法:

.items[].data.cData
  |= map(if .key == "toModify" then .key = "MODIFIED" else . end)

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多