Update JSON object using jq

Gists

Achieving the following conversion using jq. In this conversion, when key2 is true, updated_ is added to the value of key1 and the value of key2 is 2 times and key2a is added by adding updated_ to the value as new property.

Conversion

From

[
  {
    "key1": "value1",
    "key2": 123,
    "key3": true
  },
  {
    "key1": "value2",
    "key2": 456,
    "key3": false
  },
  {
    "key1": "value3",
    "key2": 789,
    "key3": true
  }
]

To

[
  {
    "key1": "updated_value1",
    "key2": 246,
    "key2a": "updated_123",
    "key3": true
  },
  {
    "key1": "value2",
    "key2": 456,
    "key3": false
  },
  {
    "key1": "updated_value3",
    "key2": 1578,
    "key2a": "updated_789",
    "key3": true
  }
]

Command

$ echo '[{"key1":"value1","key2":123,"key3":true},{"key1":"value2","key2":456,"key3":false},{"key1":"value3","key2":789,"key3":true}]' | jq '[.[] | select(.key3 == true) |= {"key1": ("updated_" + .key1), "key2": (.key2 * 2), "key2a": ("updated_" + (.key2|tostring)), "key3": .key3}]'

Testing

https://jqplay.org/s/RbKiioures

 Share!