Parse rest api content - json

My rest API returns something like:
{"UserInfo":[{"userName":"zbradford","firstName":"Zoe","lastName":"Bradford","emailAddress":"ZBradford#ABC.COM"}]}
I would like to let it return only the email address value: ZBradford#ABC.COM
Here is my code:
import groovy.json.JsonSlurper;
def slurper = new JsonSlurper()
def jsonResponse = slurper.parseText(resp)
jsonResponse.UserInfo.emailAddress.join(',')
I got a java null error, any suggestion on my code? Thanks

Has to be a json string to parse.
import groovy.json.JsonSlurper
def str = '{"UserInfo":[{"userName":"zbradford","firstName":"Zoe",
"lastName":"Bradford","emailAddress":"ZBradford#ABC.COM"}]}'
def slurper = new JsonSlurper().parseText(str)
assert slurper.UserInfo[0].emailAddress == 'ZBradford#ABC.COM'
Have a look here.

Related

Groovy. How can I get json elements in array

there is such a JSON: https://restcountries.com/v3.1/all
I just want to have a choice "translations" -> "ita" -> "common"
HTTPBuilder getHttpBuilder() {
new HTTPBuilder('https://restcountries.com/')
}
def http = httpBuilder.request(Method.GET, ContentType.JSON){
uri.path = 'v3.1/all'
uri.query = [fields: 'translations,ita,common']
response.success = { resp, json ->
log.error(json.toString()) //string
log.error(JsonOutput.toJson(json).br) //json
log.error(JsonOutput.prettyPrint(JsonOutput.toJson(json))) //formated json
}
}
but I always get either a general view or nothing of what is needed
Help me to understand! Thank you!
Found this solution for me. Maybe someone else will stumble upon it too.
import groovy.json.JsonOutput
import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import groovy.json.JsonSlurper
HTTPBuilder getHttpBuilder() {
new HTTPBuilder('https://restcountries.com/')
}
def http = httpBuilder.request(Method.GET, ContentType.JSON){
uri.path = 'v3.1/all'
}
def tempJson = JsonOutput.toJson(http)
def resultParseJson = parseJsonText(tempJson)
def needResult = resultParseJson.translations.ita.common
def parseJsonText(String textJson){
def jsonSlurper = new JsonSlurper()
return jsonSlurper.parseText(textJson)
}
needResult - what I need.
Perhaps someone will have a more beautiful or correct solution - I will be grateful. But so far this result is satisfactory.

Python AWS lambda JSON serialization issue

I am currently writing the aws lambda function with python to http post requests
apprantly its failing to serialize json headers
here my mode
import json
from botocore.vendored import requests
API_ENDPOINT = "https://api.someservices.com/v1/aws_accounts"
API_KEY = "asdfasdfasdfasdfasdf"
externalID ="dadsfasdfasdfasd"
def api_post(account_id, rolearn, account_name):
headers = {"Content-Type" : "application/json", "api_key" : API_KEY}
data = {"name":account_name,"authentication":{"protocol": "assume_role","assume_role_arn":rolearn,"assume_role_external_id":externalID}}
json_data = json.dumps(data)
response = requests.post(url = API_ENDPOINT,headers=headers, data=json_data)
print(response)
return response
this is the error I am getting
def lambda_handler(event, context):
result = update_ch(event['account_id'],event['rolearn'],event['account_name'])
return result
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: is not JSON serializable
This issue has been sorted out . I was using wrong library

How to parse the json response returned from the HttpBuilder in Groovy?

The following is what GitHub returns from a REST GET method. How to parse it using JSON?
response.success = { resp, reader ->
result = reader.text
}
[{"login":"ghost","id":1,"avatar_url": ....},{"login":"github-enterprise","id":2,"avatar_url": ....}]
You can use awesome tool for working with json - json slurper:
def slurper = new JsonSlurper()
def result = slurper.parseText(result)
def firstLogin = result[0].login
def secondId = result[1].id

how to specify variables in JSON object in integration test in grails

I'm writing an integration test for an API in grails. This API under test takes a JSON request and returns a JSON response only. Lets say the request JSON is :
{ "param1":value1,"param2":value2}
In this request, value1 and value2 depends on some other variables. So how can i put them in request JSON
A code snippet :
void testMethod(){
def controller = new DummyController()
Long param1Value = getValue(10)
Long param2Value = getValue(20)
controller.request.content = '{"param1":<param1Value>,"param2":<param2Value>}'
controller.methodUnderTest()
def response = controller.response.json
}
In this how can i specify param1value and param2value for param1 and param2 parameters respectively. Please help!
You can use JsonBuilder as below.
void testMethod(){
def controller = new DummyController()
def reqJson = new groovy.json.JsonBuilder()
reqJson {
params1 getValue(10)
params2 getValue(20)
}
controller.request.content = reqJson.toString()
controller.methodUnderTest()
def response = controller.response.json
}
or use """ or slashy string for the json string as:
controller.request.content = """{"param1":"$param1Value","param2":"$param2Value"}"""
controller.request.content = /{"param1":"$param1Value","param2":"$param2Value"}/

Grails: Error when fetching and parsing 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
}
}