I have a groovy script, it does an easy API call, and I am getting as response a JSON body.
How can I get, from the JSON body, a single value, and use it as a variable?
newRelease.request(GET) { req ->
requestContentType = ContentType.JSON
headers.'X-Octopus-ApiKey' = 'API-xxx'
response.success = { resp, JSON ->
return JSON
}
response.failure = { resp ->
return "Request failed with status ${resp.status}"
}
}
and this is the response
[DeploymentProcessId:deploymentprocess-Projects-370, LastReleaseVersion:null, NextVersionIncrement:0.0.41, VersioningPackageStepName:null, Packages:[], Links:[Self:/api/Spaces-1/deploymentprocesses/deploymentprocess-Projects-370/template]]
So what I am trying to extract is the NextVersionIncrement.
Any idea?
Related
I have the following Groovy script (not a Grails app) that is returning a JSON-like, but it is not strictly valid JSON.
String baseURL = 'https://test.com'
File userFile = new File("./user.json")
def client = new HTTPBuilder(baseUrl)
client.headers['Content-Type'] = 'application/json'
client.request(GET, JSON) { req ->
requestContentType = JSON
headers.Accept = 'application/json'
response.success = { resp, json ->
userFile.append json.toString()
println JsonOutput.toJson(json.toString())
}
}
I am trying to create a JSON output file. I have tried using JsonOutput.prettyPrint and I looked at JsonBuilder, but that looks like I would have to build the JSON structure manually when Groovy should support the output. This is what I am getting back.
{AssetNumber=AssetNumber1, DeviceFriendlyName=FriendlyName1, PhoneNumber=17035551231, SerialNumber=SerialNumber1, Udid=Udid1, UserEmailAddress=user1#email.com, UserId=userId1, UserName=userName1}
As I said, this is JSON-like, but not strictly valid. I was expecting something like:
{"AssetNumber": "AssetNumber1", "DeviceFriendlyName": "FriendlyName1"....}
Any ideas?
It works perfectly fine (groovy v 2.3.6):
import groovy.json.*
def pretty = JsonOutput.prettyPrint(JsonOutput.toJson([1:2]))
assert pretty == """{
"1": 2
}"""
In this closure:
response.success = { resp, json ->
userFile.append json.toString()
println JsonOutput.toJson(json.toString())
}
You're getting an instance of Map under json variable. You do not need to turn it into a string. Instead use:
userFile.append JsonOutput.toJson(json)
println JsonOutput.toJson(json)
I have a Grails service that sends a request to the JIRA REST API and returns JSON - When I try to use JsonSlurper to parse the JSON, I get the following error:
ERROR errors.GrailsExceptionResolver - JsonException occurred when processing request: [GET] /osmDash/jira/storyComplete
Lexing failed on line: 1, column: 1, while reading 'j', no possible valid JSON value or punctuation could be recognized.
Here is the code in the controller:
def jsonFile = jiraService.fetchJQL('issuetype=Story AND status in (Resolved,Closed,Done) AND resolved>=-30d') as JSON
def jiraSlurper = new JsonSlurper()
def jiraResult = jiraSlurper.parseText('jsonFile').total
And this is what the JSON looks like when I render it in the page:
{"total":1356,"issues":[],"startAt":0,"maxResults":0}
I was looking at groovy.json.JsonSlurper parse JSON, which seems simliar, but I couldn't get this method to work. I'm looking specifically to assign the "total" value to a variable.
This is the service that is returning the JSON:
def fetchJQL(String jql, Integer maxResults = 0, def fields = null) {
jira.request(POST, JSON) { req ->
uri.path = '/rest/api/2/search'
headers.'Authorization' = authHash
body = [jql: jql, maxResults: maxResults, fields: fields]
response.success = { resp, json ->
return json
}
response.failure = { resp ->
println resp.statusLine.statusCode
println resp.statusLine
}
}
I am using this code for GETting a JSON object from the URL using Groovy: the URL that I use is a HTTPS URL so when I test the code I get a 403 error, after Google it I understand that I need to use a HttpBuilder SSL but I don't understand how can I do it.
the code is :
def getJson(Integer id) {
def adress = new HTTPBuilder("https://api.XXXY.com")
def path="/vls/v1/etudiants/${id}?b=my&apiKey=99990"
//Get request
adresseServeur.request(Method.GET, JSON) {
uri.path = path
headers.Accept = 'application/json'
// success response handler
response.success = { resp, json ->
retourJson = json
}
// failure response handler
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
I have a service that I am built\using returning data in the below format.
def responseData = [
'results': results,
'status': results ? "OK" : "Nothing present"
]
render(responseData as JSON)
The output looks like this, I have verified the output according to Fiddler
{"results":[{"class":"com.companyName.srm.ods.territory.Apo","id":2,"apoId":"5T9B0"}],"status":"OK"}
This is a simple POST call with a body of parameters from a search.
Using HTTPBuilder I get a different result
http.request(groovyx.net.http.Method.POST, groovyx.net.http.ContentType.URLENC) {req ->
uri.path = restUrl
body = requestData
response.success = {resp, json ->
println resp.statusLine.statusCode
println resp.statusLine
def slurper = new JsonSlurper()
String s = json.toString()
println s
returnJson = slurper.parseText(s)
}
response."422" = {resp, json ->
println ${resp.statusLine}
}
response.failure = {resp ->
println ${resp.statusLine}
}
}
["results":[{"class":"com.companyName.srm.ods.territory.Apo","id":2,"apoId":"5T9B0"}],"status":"OK":null]
This turns into a Mapped pair where the key is the JSON and the value is null, which is confusing as to why the HTTPBuilder is doing that.
In order to parse to JSON, I have to the following additional coding
s = s.replace(':null]', '')
s = s.replace('[', '')
This seems overly complicated for this type of implementation.
I have turned debug and nothing interesting is coming from that.
Any ideas
I use builder 0.7.1 and get json response the next way:
http.request(Method.POST, ContentType.TEXT) {
uri.path = pathToService
headers.'User' = user
headers.Accept = 'application/json'
body = requestBody //here I post some json
response.success = { resp, reader ->
//println reader.text;
println "response status: ${resp.statusLine}"
return = reader.text
}
response.failure = { resp, reader ->
println "Request failed with status ${resp.status}"
reader.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
}
I'm trying to see if a specific string exists in an html page but I can't seem to find an easy way to get the string that represents the body.
I've attempted:
http.request(Method.GET, { req ->
uri.path = '/x/app/main'
response.success = { resp, reader ->
assert resp.status == 200
println reader.text.startsWith('denied')
}
response.failure = { resp ->
fail("Failure reported: ${resp.statusLine}")
}
})
but reader.text is a NodeChildren object.
How do I get the html (or more specifically, the contexts of the body) as a string?
You can get an input stream directly off of the response. Try this:
http.request(Method.GET, { req ->
uri.path = '/x/app/main'
response.success = { resp ->
assert resp.status == 200
println resp.entity.content.text.startsWith('denied')
}
response.failure = { resp ->
fail("Failure reported: ${resp.statusLine}")
}
})