Groovy: Correct invalid JSON as per XML specifications - json

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

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)

reading name of json using groovy

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

Django Invalid JSON Response

The following code produces the JSON given below. But when I validate it from JSON lint, it is invalid. What am I doing wrong here?
def json_candidate_get(request, model, m_id=None):
response = {'message' : 'Incorrect Json'}
try:
obj = model.objects.filter(pk=m_id)
ce = Candidate_profiles.objects.filter(pk=m_id)
cw = Candidate_company_profiles.objects.filter(pk=m_id)
response = json.dumps({ 'TechnologiesValue':[],'Technologies': [] })
except Exception as e:
logging.exception("Exception"+str(e))
return response
#is_login()
def candidate_create(request,m_id=None,token=None):
response_data = {'message': 'unsuccessfull'}
if token is not None:
try:
if request.method == 'GET':
response_data = json_candidate_get(request,Candidates,m_id)
print response_data
#response_data = serializers.serialize('json', response_data)
except Exception as e:
logging.exception(e)
return HttpResponse(response_data, content_type="application/json")
JSON:
{
TechnologiesValue: [0]
Technologies: [0]
}
The json.dumps function is meant to convert certain Python objects to a a JSON string. But you are already serializing your model instances (via QuerySets) to JSON strings, and json.dumps is trying to convert these strings into JSON all over again--it only knows that you've passed it str objects, not that these str objects represents JSON.
The JSON encoder used by json.dumps only knows how to convert a handful of built-in types:
Python 2
Python 3
So what you need to do is convert your model instances to one of these types. The easiest solution would be to use django.forms.models.model_to_dict on each element of your QuerySets, like so:
from django.forms.models import model_to_dict
response = json.dumps({
'candidate': [model_to_dict(x) for x in obj],
'CandidateEducationProfile': [model_to_dict(x) for x in ce],
...
)

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,

How do I get Value from a converted String

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"