'How to change values json groovy

I have json like this:

"tags":[
{"tag":"TAG1","value":"VALUE1"},
{"tag":"TAG2","value":"VALUE2"},
{"tag":"TAG3","value":"VALUE3"},
{"tag":"TAG4","value":"VALUE4"}]

Is it possible to change values (VALUE1, VALUE2 etc) to something else instead of current json values?

Appreciate any help!



Solution 1:[1]

Is it possible to change values (VALUE1, VALUE2 etc) to something else instead of current json values?

Yes.

You could do something like this:

import groovy.json.JsonSlurper

String jsonInputString = '''
{"tags":[
{"tag":"TAG1","value":"VALUE1"},
{"tag":"TAG2","value":"VALUE2"},
{"tag":"TAG3","value":"VALUE3"},
{"tag":"TAG4","value":"VALUE4"}]}
'''
def json = new JsonSlurper().parseText(jsonInputString)
json.tags[0].value = 'updated value'
json.tags[1].value = 'another updated value'

println json

That will output the following:

[tags:[[tag:TAG1, value:updated value], [tag:TAG2, value:another updated value], [tag:TAG3, value:VALUE3], [tag:TAG4, value:VALUE4]]]

Update:

The requirements aren't clear but if you want to dynamically find the elements you want to update, you could do something like this:

def json = new JsonSlurper().parseText(jsonInputString)
json.tags.find { it.tag == 'TAG1' }?.value = 'updated tag1'
json.tags.find { it.tag == 'TAG2' }?.value = 'updated tag2'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1