Iterate through two loops when building the JSON String - json

I am invoking a restful service to get the available documents on the the server where I am getting the JSON as s response. I am building the JSON String with the JSONBuilder so when invoking the this link
http://localhost:8080/httpConnector/Rest/Documents?Accept=application/json
I am getting the JSON String below:
{
"results": [
{
"result": {
"name": "Test traisy",
"version": "sdvdsv",
"author": "sdvdsv"
}
},
{
"result": {
"name": "Jaspersoft Ultimate guide",
"version": "sdfdsv",
"author": "sdvdsv"
}
},
{
"result": {
"name": "Dohrn",
"version": "12.19.00",
"author": "sdfdsf"
}
}
]
}
Code
String accept = getValue("Accept");
accept = "application/xml";
if ("application/xml".equals(accept)){
builder=new groovy.xml.MarkupBuilder(writer);
}else{
builder=new groovy.json.JsonBuilder();
}
builder{
results foaList.collect{
[
//Here I want to loop through the otaList to do something like that "ota.getName(), foa.getFlexiObject().getByString(ota.getName())"
result: [
name: it.getFlexiObject().getByString("name"),
version: it.getFlexiObject().getByString("version"),
author: it.getFlexiObject().getByString("author")
]
]
}
}
Now I want to add the properties programatically. Therefore I have to loop through the otaList to do something like that
builder.'results'() {
for(FlexiObjectAttachment foa: foaList){
for(ObjectTypeAttribute ota : otaList){
param.put(ota.getName(), foa.getFlexiObject().getByString(ota.getName()));
}
result(param);
}
}
this version just works for the xml respose.

What you can try is to do the combination of foa and ota directly in your collect call.
That way your initially created dict would have the correct structure.
Something like the example below
def foaList = [1, 2, 3, 4]
def otaList = ['A', 'B', 'C']
foaList.collect { foa ->
result = [name: "Name$foa", version: "v$foa", author: "Author$foa"]
otaList.each { ota -> result[ota] = "$ota$foa" }
[ result: result ]
}

Related

Looping through groovy object(List) using each{it} and pass the the elements into a json payload in Jenkins

I have a list containing the name of workspaces in groovy Jenkinsfile. I wrote an each() loop to iterate through the list and use the names in the endpoint below to get the workspace ID from the api response.
def getWorkspaceId() {
def result = []
Listworkspace.each{
def response = httpRequest(
customHeaders: [
[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
[ name: "Content-Type", value: "application/vnd.api+json" ]
],
url: "https://app.terraform.io/api/v2/organizations/${TF_ORGNAME}/workspaces/$it
)
def data = new JsonSlurper().parseText(response.content)
println ("Workspace Id: " + data.data.id)
result << data.data.id
}
return result
}
After getting the IDs, I want to pass them as part of a json payload.
def buildPayload() {
def workspaceID = new JsonSlurper().parseText(getWorkspaceId())
workspaceID.each{
def payload = """
{
"data": {
"attributes": {
"is-destroy":false,
"message":
},
"type":"runs",
"relationships": {
"workspace": {
"data": [
{"id": "$it", "type": "workspaces"}
]
}
}
}
}
}
"""
return payload
}
Is there a way I can iterate through the list of IDs returned and append each json object for the key "data" after iteration. See the code below
"relationships": {
"workspace": {
"data": [
{"id": "id1", "type": "workspaces"},
{"id": "id2", "type": "workspaces"},
{"id": "id3", "type": "workspaces"}
]
When making the api call, it throws a 400 Bad request error. I tried to print the payload and I found out it attaches the whole list of IDs to the payload.
Any suggestion will be greatly appreciated. Thank you.
def buildPayload() {
def workspaceID = new JsonSlurper().parseText(getWorkspaceId())
workspaceID.each{
def payload = """
{
"data": {
"attributes": {
"is-destroy":false,
"message":
},
"type":"runs",
"relationships": {
"workspace": {
"data": [
[id1, id2, id3]
]
}
}
}
}
}
"""
return payload
}
I'd recommend using the JsonOutput class to make your life easier. In essence, as long as your getWorkspaceId() method is returning a list of ids, you can do something like this:
import groovy.json.JsonOutput
def buildPayload(def ids) {
def payload = [
data: [
attributes: [
"is-destroy": false,
"message" : "",
],
type: "runs",
relationships: [
workspace: [
data: ids.collect {
return [id: it, type: "workspaces"]
}
]
]
]
]
return JsonOutput.toJson(payload)
}
This will take each id in your ids list and build a map where each id is identified by its number and the type: workspaces key pair. This is all then included in the larger payload.

how can I insert variables into json file when using terraform

this is the module folder structure
the json definition file (machine_definition.json)
{
"Comment": "A Hello World example of the Amazon States Language using Pass states",
"StartAt": "Hello",
"States": {
"Hello": {
"Type": "Pass",
"Result": "Hello",
"Next": "World"
},
"World": {
"Type": "${var.test}",
"Result": "World",
"End": true
}
}
}
for example I'm trying to enter var.test in here.
how to make the json file detect my variables?
here is the step function definition
module "step-functions" {
source = "terraform-aws-modules/step-functions/aws"
name = "env-${var.environment}-state-machine"
definition = file("${path.module}/machine_definition.json")
tags = var.tags
service_integrations = {
xray = {
xray = true
}
}
cloudwatch_log_group_name = "env-${var.environment}-state-machine-logGroup"
attach_policies = true
number_of_policies = 2
policies = ["arn:aws:iam::aws:policy/AmazonS3FullAccess", "arn:aws:iam::aws:policy/AWSLambda_FullAccess"]
}
Variables cannot be added to a file that way. In order to achieve what you want, you need to use the templatefile [1] built-in fuction. To achieve this you need a bit of code change:
definition = templatefile("${path.module}/machine_definition.json", {
type = var.test
})
Then, in the JSON file, you need to reference the templated variable (type) like this:
{
"Comment": "A Hello World example of the Amazon States Language using Pass states",
"StartAt": "Hello",
"States": {
"Hello": {
"Type": "Pass",
"Result": "Hello",
"Next": "World"
},
"World": {
"Type": "${type}",
"Result": "World",
"End": true
}
}
}
This should render the file properly.
[1] https://developer.hashicorp.com/terraform/language/functions/templatefile

Unable to parse json string using JsonPath in rest assured

I'm trying to parse a given JSON string and abstract some fields from it.
my Test method looks like this
Steps followed
Making a rest api call and getting response using restassured
response is stored in Response object from restassured
From response ResponseBody is being extracted using getBody() method in ResponseBody object
ResponseBody object is being converted to string using asString()
JsonPath object is being created from string value
Json is parsed by providing Jway Expression
#Test
Response searchResult = this.getEndPoint().SearchRecallAgreement(payload);
ResponseBody b = searchResult.getBody();
String responseBody = b.asString();
JsonPath j = new JsonPath(responseBody);
List<String> ls = j.getList("payload.returnTerms[*].returnTermPolicies[?(#.policyType == 'RC_ITEMS_POLICY')].policies[?(#.policyKey=='/575330172')].policyKey");
System.out.println(ls);
Error in console
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: Unexpected input: '['; Expecting <EOF> # line 1, column 46.
RootObject.payload.returnTerms[*].return
Json string looks like
{
"status": "OK",
"header": {
"headerAttributes": {}
},
"errors": [],
"payload": {
"totalCount": 6,
"returnTerms": [
{
"returnTermType": "RECALL_AGREEMENT",
"returnTermPolicies": [
{
"policyType": "RC_ITEMS_POLICY",
"keyTemplate": "/itemNo/storeNo",
"policies": [
{
"policyKey": "/583919815",
"attributeList": [
]
},
{
"policyKey": "/575330172",
"attributeList": [
]
},
{
"policyKey": "/583919815/2345"
}
]
}
]
},
{
"returnTermPolicies": [
{
"policyType": "RC_ITEMS_POLICY",
"keyTemplate": "/itemNo/storeNo",
"policies": [
{
"policyKey": "/583919815",
"attributeList": [
]
},
{
"policyKey": "/575330172",
"attributeList": [
]
},
{
"policyKey": "/583919815/2346"
},
{
"policyKey": "/583919815/2345"
}
]
}
]
}
]
}
}
Expected output :
[
"/575330172",
"/575330172"
]

How to feed a value into a field in a json array in Gatling?

I am using Gatling to test an API that accepts a json body like below:
{
"data": {
"fields": [
{
"rank": 1
},
{
"name": "Jack"
}
]
}
}
I have created a file feeder.json that contains array of json objects like above.
Below is the feeder.json
[
{
"data": {
"fields": [
{
"rank": 1
},
{
"name": "Jack"
}
]
}
}
]
I have created another file template.txt that contains the template of above json.
Below is the template.txt
{
"data": {
"fields": [
{
"rank": ${data.fields[0].rank} //this is not working
},
{
"name": "Jack"
}
]
}
}
val jsonFeeder = jsonFile("feeder.json").circular
scenario("Test scenario")
.feed(jsonFeeder)
.exec(http("API call test")
.post("/data")
.body(ElFileBody("template.txt"))
.asJson
.check(status is 200))
I am feeding the feeder.json and also sending json body from template.json. The 'rank' property values should get set from feeder into the json body. But I am getting an error 'Map named 'data' does not contain key 'fields[0]'. Stuck with this.
Access by index syntax uses parens, not square braces.
#{data.fields(0).rank}

Get _id from MongoDB using Scala

For a given JSON how do I get the _id to use it as an id for inserting in another JSON?
Tried to get the ID as shown below but does not return correct results.
private def getModelRunId(): List[String] = {
val resultsCursor: List[DBObject] =
modelRunResultsCollection.find(MongoDBObject.empty, MongoDBObject(FIELD_ID -> 1)).toList
println("resultsCursor >>>>>>>>>>>>>>>>>> " + resultsCursor)
resultsCursor.map(x => (Json.parse(x.toString()) \ FIELD_ID).asOpt[String]).flatten
}
{
"_id": ObjectId("5269723bd516ec3a69f3639e"),
"modelRunId": ObjectId("5269723ad516ec3a69f3639d"),
"results": [
{
"ClaimId": "526971f5b5b8b9148404623a",
"pricingResult": {
"TxId": 0,
"ClaimId": "Large_Batch_1",
"Errors": [
],
"Disposition": [
{
"GroupId": 1,
"PriceAmt": 20,
"Status": "Priced Successfully",
"ReasonCode": 0,
"Reason": "RmbModel(PAM_DC_1):ProgramNode(Validation CPG):ServiceGroupNode(Medical Services):RmbTerm(RT)",
"PricingMethodologyId": 2,
"Lines": [
{
"Id": 1
}
]
}
]
}
},
If you want to find objectId's:
import com.mongodb.casbah.Imports._
collection.find(MongoDBObject(/*query*/)).map(_._id)
If you want to query by id:
collection.findOneByID(/*id*/)
I suppose you are using Casbah, the official Driver for Scala.
You just need to modify the map function :
resultsCursor.map { x => x.as[org.bson.types.ObjectId](FIELD_ID)}
Casbah does the deserialization from BSON to Scala object, so you don't have to do it yourself !