Home > Software engineering >  Groovy Json parsing
Groovy Json parsing

Time:09-16

Hi i am bit new and need help to parse a hash, for example data: in current example,i want to loop through all keys TEST-A,TEST-B,TEST-C and change their value (app-id), for now using jsonslurper i can parse and edit value per key like this:

parsed.'TEST-A'[0].app_id = a

but what i want is to read keys and assign values (these value i will be reading as String)


import groovy.json.*
data = '''
{
    "TEST-A":   [{ "app_id":"aaa" }],
    "TEST-B":   [{ "app_id":"bbb" }],
    "TEST-C":   [{ "app_id":"ccc" }]
}'''

def parsed = new JsonSlurper().parseText(data)
String a= 'test';
parsed.'TEST-A'[0].app_id = a
def result = JsonOutput.toJson(parsed)
println "result: $result"

CodePudding user response:

Reading and writing your "json" object through can look like:

import groovy.json.*
data = '''
{
    "TEST-A":   [{ "app_id":"aaa" }],
    "TEST-B":   [{ "app_id":"bbb" }],
    "TEST-C":   [{ "app_id":"ccc" }]
}'''

def parsed = new JsonSlurper().parseText(data)
String a= 'test';

parsed.each{ it.value[0].app_id = a } // < here is MAGIC!

def result = JsonOutput.toJson(parsed)
println "result:\n${JsonOutput.prettyPrint(result)}"

gives

result:
{
    "TEST-A": [
        {
            "app_id": "test"
        }
    ],
    "TEST-B": [
        {
            "app_id": "test"
        }
    ],
    "TEST-C": [
        {
            "app_id": "test"
        }
    ]
}

CodePudding user response:

parsed.each{k,v-> 
  if(k in ['TEST_A','TEST_B','TEST_C']) v[0].app_id = a 
}
  • Related