Merge two JSONs from groovy - json

I have 2 JSON files and I want to merge those 2 and create one JSON message using groovy. Based on the "type" value I'm going to merge those two JSON files.
If the given "type" of JSON objects of JSON message 1 does not exist
in the JSON message2, the relevant JSON object should be contained in the output JSON message.
All the JSON objects from JSON message2 should be contained in the
output JSON message
Expected sample formats is shown below
Input JSON message1
{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]
Input JSON message2
[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]
Expected JSON
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"},{"name":"SecondFile","type": "error"}]}
I used the below groovy code.
JsonBuilder jsonBuilder = new JsonBuilder(JSON1)
jsonBuilder.content.message= JSON2
def updatedBody = jsonBuilder.toString()
From the above code, I got the below message.
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]}
Any help sorting this would be much appreciated.

Try using JsonSlurper:
import groovy.json.*
​def json1 = '{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]}'​​​​​​​​​​​​​
def json2 = '[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]'
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.message+=json2Obj
println JsonOutput.toJson​(json1Obj)​
This prints:
{"message":[{"name":"HelloFile","type":"input"},{"name":"SecondFile","type":"error"},{"name":"NewFile","type":"input"},{"name":"MyFile","type":"output"}]}

Related

Groovy: JSON Parsing

Seeing an interesting issue, not sure this is to do with parser or the way it suppose to parse. Any help is appreciated
import groovy.json.JsonSlurper
def dMatch = '''[{"match":{"keyId":"A-102161-application"}},{"match":{"keyId":"A-102162-application"}},{"match":{"keyId":"A-102163-application"}},{"match":{"keyId":"A-102164-application"}},{"match":{"keyId":"A-102165-application"}}]'''
println "T1:: List: " + dMatch
def parser = new JsonSlurper()
def exclude = parser.parseText(dMatch)
println "T2:: Obj: " + exclude.toString()
println "----------------------------------------------------"
Output :
T1:: List: [{"match":{"keyId":"A-102161-application"}},
{"match":{"keyId":"A-102162-application"}},
{"match":{"keyId":"A-102163-application"}},
{"match":{"keyId":"A-102164-application"}},
{"match":{"keyId":"A-102165-application"}}]
T2:: Obj: *[[match:[keyId:A-102161-application]],
[match:[keyId:A-102162-application]],
[match:[keyId:A-102163-application]],
[match:[keyId:A-102164-application]],
[match:[keyId:A-102165-application]]]*
The parsed object supposed to be same as the string but all the values were converted as array list of map.
Any idea why this is generating object like this ? When this is sent to camunda it complains
org.camunda.bpm.engine.ProcessEngineException: Cannot serialize object in variable 'exclude': groovy.json.internal.LazyMap
Use JsonSlurperClassic() - it produces standard HashMap that is serializable.
And if you want to convert object back to json use Json output.toJson(obj)

Groovy script json response length

I need to find json response length. Sample response looks like below:
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
As two parameters are present in resource. So, i should have got response as 2.
Please let me know hoe i can find json length as 2
This is the working solution, try this
import groovy.json.JsonSlurper // import this class
def jsonText = '''{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}'''
def json = new JsonSlurper().parseText(jsonText)
println "Json length---------->"+json.resource.size()
If you have the JSON object, you don't need to parse JSON string to json, yo can directly do the following,
println jsonObject.resource.size() // Here resource is the key(sub node) inside your json
If you want to get the length of parent JSON key, just do as follows,
println jsonObject.size()
Based on your question, it appears that you would like to know the count of properties within a JSON object. So we can do that by following these steps:
STEP 1 : Parse the response string into JSON object
STEP 2 : Convert JSON object into groovy Map object
Step 3 : Call size() method on Map object to get the elements count within the map object
So your code would like this :
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def response = jsonSlurper.parseText('{ "resource": {"name":"aaaaaaaaaaa","emailid":"bbbbbbbbb"}}')
def object = (Map)response.resource
log.info object.size()
So your output will be 2. You can try adding more elements to JSON object check if it works.
Hope this helps :)

SoapUi Assertions - Use a string as a json path with groovy

I am using groovy to automate some tests on SoapUI, and I wanted to also automate assertions in a way I would get a field's name and value from a *.txt file and check if the wanted field does exist with the wanted value in the SOapUI response.
Suppose I have the following json response:
{
"path" : {
"field" : "My Wanted Value"
}
}
And from my text file I would have the following two strings :
path="path.field"
value="My Wanted Value"
I tried the following :
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response
assert json.path==value;
But of course it doesn't work.
Any idea how can I get it done please?
Thank you
I think your problem is to access a json value from a path based with . notation, in your case path.field to solve this you can use the follow approach:
import groovy.json.JsonSlurper
def path='path.field'
def value='My Wanted Value'
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step to
// find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Additionally I'm not sure if you're also asking how to read the values from a file, if it's also a requirement you can use ConfigSlurper to do so supposing you've a file called myProps.txt with your content:
path="path.field"
value="My Wanted Value"
You can access it using the follow approach:
import groovy.util.ConfigSlurper
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
println config.path // path.field
println config.value // My Wanted Value
All together (json path + read config from file):
import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Hope this helps,

Using Groovy's JsonSlurper for actual POGO mapping?

I've seen countless examples of JsonSlurper used to parse JSON text and create a "JSON object" out of it:
def jsonObject = jsonSlurper.parseText(jsonText)
But what if the JSON text represent one of my FizzBuzz objects? Can I use JsonSlurper to map the JSON object into a FizzBuzz instance? If so, how?
After parsing JSON with JsonSlurper You receive a Map. If FizzBuzz has a Map (see here) constructor it should work when parsed Map is passed to constructor.
See the following example:
import groovy.json.JsonSlurper
def json = """{ "name": "John", "age": 127 }"""
def parsed = new JsonSlurper().parseText(json)
def person = parsed as Person
assert person.age == 127
assert person.name == 'John'
class Person {
String name
int age
}

Reading json content from file to do assertion functional testing in SOUP UI using Groovy scripts

I am using SOAP UI to test the RESTful web services. To automate the regression testing, I need to compare the actual response and expected output. I have the actual response to the request parsed into a json object. I have the expected output in a text file with JSON content.
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def responseAsJsonObject = slurper.parseText response
//? Read json file content and parse it as an json object
assert fileContentAsJsonObject == responseAsJsonObject
I need a way to read this JSON content from the text file and parse into a json object in Groovy.
def fileContent = new File('D:\\test.json').text
def fileContentAsJsonObject = slurper.parseText fileContent
It works! Get the file content using .text and parse the fileContent to the jsonSlurper, which generates you the json object.
Its better to use log.info to write on log console and debugg.