How to translate groovy map to json - groovy

I have the below code in Jenkins pipeline:
stage ("distribution"){
steps{
script{
def rules = [
service_name: "core",
site_name: "*",
city_name: "*",
country_codes: ["*"]
]
amd_distribution_distribute_bundle distribution_rules: rules
}
}
}
As you can see, it's a map parameter. How can I convert it to the JSON file using Groovy code? At the end it should look like:
{
"distribution_rules": [
{
"service_name": "core*",
"site_name": "*",
"city_name": "*",
"country_codes": ["*"]
}
]
}
I tried the below command but it didn't help:
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
def call(Map parameters)
{
def DISTRIBUTION_RULES = parameters.distribution_rules
def json = new groovy.json.JsonBuilder()
json rootKey: "${DISTRIBUTION_RULES}"
writeFile file: 'rootKey', text: JsonOutput.toJson(json)
}

There is no need to mix JsonBuilder and JsonOutput in your amd_distribution_distribute_bundle.groovy file. The JsonOutput.toJson(map) method takes a regular Map and translates it to the JSON object equivalent. By default it creates a flat single line file. If you expect to get so-called pretty print, you need to use combination of JsonOutput.prettyPrint(JsonOutput.toJson(map)).
Flat print
import groovy.json.JsonOutput
def call(Map parameters) {
def DISTRIBUTION_RULES = parameters.distribution_rules
writeFile file: 'rootKey', text: JsonOutput.toJson([distribution_rules: [DISTRIBUTION_RULES]])
}
Output:
$ cat rootKey
{"distribution_rules":[{"service_name":"core","site_name":"*","city_name":"*","country_codes":["*"]}]}%
Pretty print
import groovy.json.JsonOutput
def call(Map parameters) {
def DISTRIBUTION_RULES = parameters.distribution_rules
writeFile file: 'rootKey', text: JsonOutput.prettyPrint(JsonOutput.toJson([distribution_rules: [DISTRIBUTION_RULES]]))
}
Output:
$ cat rootKey
{
"distribution_rules": [
{
"service_name": "core",
"site_name": "*",
"city_name": "*",
"country_codes": [
"*"
]
}
]
}%

Related

How to create json array and values using Groovy jsonBiulder

trying to create the below json structure with groovy jsonBuilder in jmeter using JSR223 sampler
{
"Catalogues":[
{
"Catalogue":{
"itemName":"XYZ",
"Level":"Class1",
"Color":"Orange",
"Id":"232f2d6820822840"
},
"sales":[
[
"7:19 PM 3-31-2022",
"gadfma53742w3585657er43"
],
[
"5:02 PM 3-30-2022",
"iytyvh53742w3585657er41"
]
]
}
]
}
I have tried the below groovy script
def json = new groovy.json.JsonBuilder()
json {
Catalogues(
[{
Catalogue {
itemName('XYZ')
Level('Class1')
Color('Orange')
Id('232f2d6820822840')
},
{
sales(
('7:19 PM 3-31-2022'), ('gadfma53742w3585657er43')
)
}
}]
)
}
log.info '\n\n\n' + json.toPrettyString() + '\n\n\n'
Output:
{
"Catalogues":[
{
"Catalogue":[
{
"itemName":"XYZ",
"Level":"Class1",
"Color":"Orange",
"Id":"232f2d6820822840"
},
{
"sales":[
"7:19 PM 3-31-2022",
"gadfma53742w3585657er43"
]
}
]
}
]
}
Problems:
If I remove the '{' before sales and after (at corresponding location), it adds sales values into catalogue
unable to include second set of sales values
I'm suggesting another way to use builder because it's easier to understand.
To declare array in groovy use [1, 2, 3]
To declare map [a:1, b:2, c:3]
So, if you replace in original json { to [ - you will get valid groovy object that corresponds to parsed json
def data = [
"Catalogues":[
[
"Catalogue":[
"itemName":"XYZ",
"Level":"Class1",
"Color":"Orange",
"Id":"232f2d6820822840"
},
"sales":[
[
"7:19 PM 3-31-2022",
"gadfma53742w3585657er43"
],
[
"5:02 PM 3-30-2022",
"iytyvh53742w3585657er41"
]
]
]
]
]
//then you could convert it to json:
def json = new groovy.json.JsonBuilder(data).toPrettyString()
log.info(json)
JsonBuilder translates Map to JSON Object and List to JSON Array
So I would recommend for better readability and clarity amending your code to look like:
def body = [:]
def Catalogues = []
def Catalogue = [:]
def entry = [:]
Catalogue.put('itemName', 'XYZ')
Catalogue.put('Level', 'Class1')
Catalogue.put('Color', 'Orange')
Catalogue.put('Id', '232f2d6820822840')
def sales = []
sales.add(['7:19 PM 3-31-2022', 'gadfma53742w3585657er43'])
sales.add(['5:02 PM 3-30-2022', 'iytyvh53742w3585657er41'])
entry.put('Catalogue', Catalogue)
entry.put('sales', sales)
Catalogues.add(entry)
body.put('Catalogues', Catalogues)
def json = new groovy.json.JsonBuilder(body)
More information:
JsonBuilder
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

How to find and get values from a json file which are in the same level?

I have a JSON file which looks like below. I am getting the parameters for name and product_version. Using both of them I need to get the relese_version and latest boolean value.
eg:- If var1 = section1 var2 = 2.6.0 then the release_version should be taken as 2.6.0.9 and latest as false in groovy.
file.json
{
"platforms": [
{
"name": "section1",
"versions": [
{
"product_version": "2.6.0",
"release_version": "2.6.0.9",
"latest": false
},
{
"product_version": "3.0.0",
"release_version": "3.0.0.3",
"latest": false
}
]
},
{
"name": "section2",
"versions": [
{
"product_version": "2.6.0",
"release_version": "2.6.0.9",
"latest": false
},
{
"product_version": "3.0.0",
"release_version": "3.0.0.3",
"latest": false
}
]
}
]
}
This is the code snippet I tried out.
filename = "file.json"
def jsonSlurper = new JsonSlurper()
parsed_json = jsonSlurper.parse(new File(filename))
release_tag = json.parsed_json.find {platforms.name == "section1".version[].product_version == "2.6.0".release_version}
println release_tag
But this didn't work. Please help me with this
You first have to find the platform by name (which could fail); next
find in the versions the product version. E.g.
def data = new groovy.json.JsonSlurper().parse("data.json" as File)
def name='section1'
def productVersion = '2.6.0'
// XXX
def result = data.platforms.find{ it.name == name }?.versions?.find{ it.product_version == productVersion }
assert result.release_version == '2.6.0.9'
assert result.latest == false
Note the use of the "elvis operator" after the first find to
short-circuit.
If you have to do many such lookups on the same data file, it might make
sense to shape the data into a better form for the lookup you are doing
(e.g. turn that into maps of maps for your two lookup keys)

How to do a POST web api call with groovy code?

I have some POST method url, 2 headers to pass and a big body in Json format, that I need to call through the Groovy code. But I am not sure on points like how to pass headers and big Json object in Groovy code for API call. Please help me on thease points. I am writin this code in visual code.
Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def post = new URL("https://xyxz/api/testRequest/generic").openConnection();
def message = '{
"test": "test",
"test1": "test1\n\t",
"test2": {
"test3": "test3",
"test4": "test4"
}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.setHeader("id","sadasdas1212134");
post.setHeader("id2","sdsd34sdsfdfdfdf");
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
println(post.getInputStream().getText());
}
Straight from the ref-doc
import groovyx.net.http.HttpBuilder
def body = [
"test": "test",
"test1": "test1\n\t",
"test2": [
"test3": "test3",
"test4": "test4"
]
]
def result = HttpBuilder.configure {
request.uri = 'https://xyxz/api/testRequest/generic'
request.headers.id = 'sadasdas1212134'
request.headers.id2 = 'sdsd34sdsfdfdfdf'
request.contentType = 'application/json'
request.body = body
}.post()
println result

Generate json body using groovy in jmeter having array inside an array

I'm trying to generate JSON body dynamically using values in csv file. For this i'm making use of JSR223 PreProcessor with groovy script.
I'm expecting the below format to be generate when i run the groovy script
{
"transactionId": "100",
"lineItems": [{
"lineItemNo": "1",
"cardInfo": {
"cardNumber": "3456"
}
},
{
"lineItemNo": "2",
"cardInfo": {
"cardNumber": "45698"
}
}
]
}
but when i execute script i'm getting below format
POST data:
{
"transactionId": "100",
"lineItems": [
{
"lineItemNo": "1",
"Cardinfo": [
9255000012794606,
9255000012794645
]
},
{
"lineItemNo": "1",
"Cardinfo": [
9255000012794606,
9255000012794645
]
}
]
}
Script to generate json body
File csvFile = new File("D:\\Project Related Docs\\Jmeter\\apache-jmeter-5.0\\bin\\Map_Performance\\Map_New_Auto_jmx\\2Cards.csv")
def cards = csvFile.readLines()
List<String> cardnumbmer = new ArrayList<>()
def counter = 1
cards.eachWithIndex{line,idx->cardnumbmer.add(line)}
log.info("size of csv = "+cardnumbmer.size())
log.info("File conents = "+cardnumbmer[0])
//build the json body
def ids = new groovy.json.JsonSlurper().parseText(cardnumbmer.toString())
log.info("cardnumbmer to string = "+cardnumbmer.toString())
def builder = new groovy.json.JsonBuilder()
builder([
transactionId:"100",
lineItems:ids.collect{[lineItemNo:"1",Cardinfo: ids.collect{carnumber: it}]}
])
//sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('',builder.toPrettyString(),'')
sampler.setPostBodyRaw(true);
--CSV FILE have cardnumbers listed in row-wise look like below
9255000012794606
9255000012794645
Request to help me to know how to fix this issue.
ids.collect{carnumber: it} is basically ids. Be explicit about returning the map: ids.collect{ [carnumber: it] }
Below code resolved the problem
//build the json body
def ids = new groovy.json.JsonSlurper().parseText(cardnumbmer.toString())
log.info("cardnumbmer to string = "+cardnumbmer.toString())
def builder = new groovy.json.JsonBuilder()
def count = 1
builder([
transactionId:"100",
//lineItems:ids.collect{[lineItemNo:"1",Cardinfo: count.collect{[carnumber: it]}]}
lineItems:ids.collect{[lineItemNo:count++,Cardinfo: [Cardnumber:it]]}
])
//sampler.getArguments().removeAllArguments()
sampler.addNonEncodedArgument('',builder.toPrettyString(),'')
sampler.setPostBodyRaw(true);

get this JSON representation of your neo4j objects

I want to get data from thisarray of json object :
[
{
"outgoing_relationships": "http://myserver:7474/db/data/node/4/relationships/out",
"data": {
"family": "3",
"batch": "/var/www/utils/batches/d32740d8-b4ad-49c7-8ec8-0d54fcb7d239.resync",
"name": "rahul",
"command": "add",
"type": "document"
},
"traverse": "http://myserver:7474/db/data/node/4/traverse/{returnType}",
"all_typed_relationships": "http://myserver:7474/db/data/node/4/relationships/all/{-list|&|types}",
"property": "http://myserver:7474/db/data/node/4/properties/{key}",
"self": "http://myserver:7474/db/data/node/4",
"properties": "http://myserver:7474/db/data/node/4/properties",
"outgoing_typed_relationships": "http://myserver:7474/db/data/node/4/relationships/out/{-list|&|types}",
"incoming_relationships": "http://myserver:7474/db/data/node/4/relationships/in",
"extensions": {},
"create_relationship": "http://myserver:7474/db/data/node/4/relationships",
"paged_traverse": "http://myserver:7474/db/data/node/4/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://myserver:7474/db/data/node/4/relationships/all",
"incoming_typed_relationships": "http://myserver:7474/db/data/node/4/relationships/in/{-list|&|types}"
}
]
what i tried is :
def messages=[];
for ( i in families) {
messages?.add(i);
}
how i can get familes.data.name in message array .
Here is what i tried :
def messages=[];
for ( i in families) {
def map = new groovy.json.JsonSlurper().parseText(i);
def msg=map*.data.name;
messages?.add(i);
}
return messages;
and get this error :
javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseText() is applicable for argument types: (com.tinkerpop.blueprints.pgm.impls.neo4j.Neo4jVertex) values: [v[4]]\nPossible solutions: parseText(java.lang.String), parse(java.io.Reader)
Or use Groovy's native JSON parsing:
def families = new groovy.json.JsonSlurper().parseText( jsonAsString )
def messages = families*.data.name
Since you edited the question to give us the information we needed, you can try:
def messages=[];
families.each { i ->
def map = new groovy.json.JsonSlurper().parseText( i.toString() )
messages.addAll( map*.data.name )
}
messages
Though it should be said that the toString() method in com.tinkerpop.blueprints.pgm.impls.neo4j.Neo4jVertex makes no guarantees to be valid JSON... You should probably be using the getProperty( name ) function of Neo4jVertex rather than relying on a side-effect of toString()
What are you doing to generate the first bit of text (which you state is JSON and make no mention of how it's created)
Use JSON-lib.
GJson.enhanceClasses()
def families = json_string as JSONArray
def messages = families.collect {it.data.name}
If you are using Groovy 1.8, you don't need JSON-lib anymore as a JsonSlurper is included in the GDK.
import groovy.json.JsonSlurper
def families = new JsonSlurper().parseText(json_string)
def messages = families.collect { it.data.name }

Resources