I have the below JSON structure and I am trying to retrieve the name order/sale/Cancel to a string variable in groovy
{"Transaction" : {"Order" : { ......
{"Transaction" : {"Sale" : { ......
{"Transaction" : {"Cancel" : { ......
I was able to get to this point, reading the JSON using JSON slurper with some research but not sure how to get read the name.. most of the articles I have seen the point to reading the values and not the name.
final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, 'UTF-8'))
Object result = jsonSlurper.parse(inReader)
I have converted from XML to JSON so if this can be done using either XML or JSON would help.
Correct would be to use :
def json = '{"Transaction" : {"Order" : "result"} }'
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json)
assert 'Order' == result.Transaction.keySet().first()
If you have JSON in String you don't need to create BufferedReader, just use parseText. After you parse JSON you can just access it by traversing properties.
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(inputStream.text);
result.Transaction.Order //result
Related
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)
I am trying to correct the Incoming JSON as I have a JSON to XML converter. I wish to replace the leading number in a field etc 1Doc1 to S_Doc1 etc. Also I Need to replace the invalid XML element names from JSON such as Slash etc. Here is my Code but it is not working:
def list = new JsonSlurper().parseText( payload )
list.each {
def oldStr = "" + it
def newStr = oldStr.replaceFirst("^[^a-zA-Z]+", "S_")
payload = payload.replaceFirst(oldStr, newStr)
}
return payload
I get the Input as is. Could anyone advise how to do this in Groovy. For example if my Input is:
{
"1Document1":
{"Record":{"Header"...….
The Output should be
{
"S_Document1":
{"Record":{"Header"......
You can use eachWithIndex and update the element in the list using key instead of trying to manipulate the input string:
import groovy.json.JsonSlurper
String json = '[{"1Document1": {"Record":{"Header": "xx"}}}, {"2Document1": {"Record":{"Header": "zz"}}}]'
def list = new JsonSlurper().parseText( json )
list.eachWithIndex {v, k ->
def newStr = (""+v).replaceFirst("^[^a-zA-Z]+", "S_")
list[k] = newStr
}
println list
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,
I have this code:
"response=3&responsetext=Duplicate transaction REFID:3154223053&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300"
I tried converting it into json format using this code:
def converted = "{\"" + resp.data.toString()
.replaceAll('=','\":\"')
.replaceAll('&','\",\"') + "\"}"
it returns the valid json format though I want to get a specific value from that string I tried doing:
println converted.responsetext.toString()
it has an error saying
No such property: responsetext for class: java.lang.String
You can convert request parameters to Map and if required to json string as below:
String str = "response=3&responsetext=Duplicate transaction REFID:3154223053&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300"
def map = str.tokenize(/&/).collectEntries {
def entity = it.tokenize(/=/)
[ entity[0], entity[1] ]
}
assert map.responsetext == "Duplicate transaction REFID:3154223053"
// Json
println new groovy.json.JsonBuilder( map ).toPrettyString()
If you want to go ahead from what you have right now instead, then below implementation should be sufficient:
def items = new groovy.json.JsonSlurper().parseText( converted )
assert items.responsetext == "Duplicate transaction REFID:3154223053"
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
}