Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active June 27, 2020 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/e8979e269fb2fd7eae535019ad83781c to your computer and use it in GitHub Desktop.
Save tanaikech/e8979e269fb2fd7eae535019ad83781c to your computer and use it in GitHub Desktop.
Update JSON object using jq

Update JSON object using jq

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment