简体   繁体   English

需要使用JQ在JSON中查找键值对并替换键值对

[英]Need to find key-value pair and replace key-value pair in JSON using JQ

I have this JSON我有这个 JSON

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

I need to find the value of the "state" key Using JQ and replace the value in JSON. I do not want to fetch it by providing the position of the key, Like我需要使用 JQ 找到“状态”键的值并替换 JSON 中的值。我不想通过提供键的 position 来获取它,就像

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

My expected output我预计 output

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

If you're willing to specify.address:如果您愿意指定地址:

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

Otherwise:否则:

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

This last will replace all .state values.最后一个将替换所有.state值。 If you only want to replace the first occurrence:如果您只想替换第一次出现:

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

And so on.等等。 It would really help all concerned if you could make the requirements clear.如果你能把要求说清楚,那真的对所有相关人员都有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM