Using jq to update objects within a JSON document if the value corresponding to a given key starts with a specified string

后端 未结 2 1261
旧时难觅i
旧时难觅i 2021-01-12 13:13

I have the given JSON and want to change the id value of all elements, which starts with test in the name element:

{
          


        
相关标签:
2条回答
  • 2021-01-12 13:52

    You can also use map, like this:

    jq '(.values)|=(map((if .name|startswith("test") then .id="NEWID"  else . end)))' file
    

    Output:

    {
      "other-value": "some-id",
      "values": [
        {
          "name": "test-2017-12-01",
          "id": "NEWID"
        },
        {
          "name": "othert",
          "id": "2"
        }
      ]
    }
    
    0 讨论(0)
  • 2021-01-12 14:10

    Please note that since the release of jq 1.5, jq has been enhanced to support the query that previously failed. For example, using the current 'master' version:

    jq -c '(.values[] | select(.name | startswith("test")).id) |= "NEWID"'
    {"other-value":"some-id","values":[{"name":"test-2017-12-01","id":"NEWID"},{"name":"othert","id":"2"}]}
    

    Using earlier versions of jq, if/then/else/end can be used in this type of situation as follows:

    .values[] |= if .name | startswith("test") then .id = "NEWID" else . end
    

    If using map, a minimalist expression would be:

    .values |= map(if .name|startswith("test") then .id = "NEWID" else . end)
    
    0 讨论(0)
提交回复
热议问题