簡體   English   中英

需要使用JQ在JSON中查找鍵值對並替換鍵值對

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

我有這個 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 中的值。我不想通過提供鍵的 position 來獲取它,就像

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

我預計 output

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

如果您願意指定地址:

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

等等。 如果你能把要求說清楚,那真的對所有相關人員都有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM