【问题标题】:Need to find key-value pair and replace key-value pair in JSON using JQ需要使用JQ查找键值对并替换JSON中的键值对
【发布时间】:2021-08-26 10:07:18
【问题描述】:

我有这个 JSON

{
  "firstName": "Rajesh",
  "lastName": "Kumar",
  "gender": "man",
  "age": 24,
  "address": {
    "streetAddress": "126 Udhna",
    "city": "Surat",
    "state": "WB",
    "postalCode": "394221"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "7383627627"
    }
  ]
}

我需要使用 JQ 找到“状态”键的值并替换 JSON 中的值。我不想通过提供键的位置来获取它,喜欢

firstName=$(cat sample-json.json | jq -r '.firstName')

我的预期输出

{
  "firstName": "Rajesh",
  "lastName": "Kumar",
  "gender": "man",
  "age": 24,
  "address": {
    "streetAddress": "126 Udhna",
    "city": "Surat",
    "state": "Bihar",
    "postalCode": "394221"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "7383627627"
    }
  ]
}

【问题讨论】:

  • 那你想怎么获取呢?
  • 所以你想改变state键的值?

标签: json jq


【解决方案1】:

如果您愿意指定 .address:

jq '.address.state = "Bihar"' sample-json.json

否则:

jq 'walk(if type == "object" and has("state") then .state = "Bihar" else . end)' sample-json.json

最后一个将替换所有.state 值。如果您只想替换第一个匹配项:

jq 'first(..|objects|select(has("state"))).state = "Bihar"' sample-json.json

等等。如果您能明确要求,这将真正帮助所有相关人员。

【讨论】:

  • 低于错误 - jq: error: walk/1 is not defined at , line 1: walk(if type == "object" and has("state") then 。 state = "Bihar" else .end) jq: 1 compile error
  • 您的 jq 版本一定很旧。如果您没有更好的选择,您可以简单地复制其定义,在线提供。例如。谷歌:def walk jq 内置
  • 使用它来安装 JQ - #!/bin/bash export PATH="$PATH:." curl -s -L github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64 > ./jq chmod +x ./jq
  • 为什么要安装一个非常旧的版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2019-12-26
相关资源
最近更新 更多