How do I get Value from a converted String - json

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"

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: Correct invalid JSON as per XML specifications

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

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],
...
)

Grails: Parsing through JSON String using JSONArray/JSONObject

I have the below JSON string coming in as a request parameter into my grails controller.
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
As you can see, the timesheetList might have multiple elements in it. In this ( above ) case, we have only one. So, I expect it to behave like an Array/List.
Then I had the below code to parse through it:
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def timesheet1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now. Any help?
1st off to simplify your code, use request.JSON. Then request.JSON.list[ 0 ] should be working