groovy to remove json unwated array label - json

I have this json and I want to remove the field item.
{ "field": "AAA", "list": { "item": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ] }}
I'm using this json slurper groovy but it's returnung null.
def myJson = '..' //above json; def jsonParser = new JsonSlurper(); def jsonObject=jsonParser.parseText(myJson); return JsonOutput.toJson(jsonObject["item"])
The expected output is:
{ "field": "AAA", "list": [ { "field01": "111", "field02": "222" }, { "field01": "333", "field02": "444" } ]}
How can I do to remove the field "item"?

def myJson = '..' //above json;
def jsonParser = new JsonSlurper();
def jsonObject=jsonParser.parseText(myJson);
jsonObject.list=jsonObject.list.item
return JsonOutput.toJson(jsonObject)

Related

Groovy script to compare 2 JSON array objects

I am trying to find the best way to compare 2 JSON Array objects using Groovy script.
JSON Obj1 =
{
"PO":
[
{
"OrderNumber": "12345",
"Location": "US",
}
{
"OrderNumber": "11223",
"Location": "US",
}
]
}
JSON Obj2 = {
"ResultPO":
[
{
"OrderNumber": "12345_00001",
"Location": "US",
"Customer": "ABC"
}
{
"OrderNumber": "98765_00002",
"Location": "US",
"Customer": "XYZ"
}
]
}
I need to return the JSON Output as below after finding the obj1 value in obj2 where OrderNumber is key identifier.
{
"ResultPO":
[
{
"OrderNumber": "12345_00001",
"Location": "US",
"Customer": "ABC"
}
]
}
Below is the sample code I have tried using JsonSlurper and findall but not able to get desired outcome.
def builder
def filterJson
filterJson = Obj2.findAll(){ it.OrderNumber.substring(0,4) == Obj1.OrderNumber.text()}
builder = new JsonBuilder(filterJson)
Try this one:
class OrderFilterSpec extends Specification {
def str1 = """{"PO":[
{"OrderNumber": "12345","Location": "US"},
{"OrderNumber": "11223","Location": "US"}
]}"""
def str2 = """{"ResultPO":[
{"OrderNumber": "12345_00001","Location": "US","Customer": "ABC"},
{"OrderNumber": "98765_00002","Location": "US","Customer": "XYZ"}
]}"""
def slurper = new JsonSlurper()
def buildResult(String first, String second) {
def (parsed1, parsed2) = [slurper.parseText(first), slurper.parseText(second)]
def filteredOrders = parsed2.ResultPO.findAll {
it.OrderNumber[0..4] in parsed1.PO.collect { it.OrderNumber }
}
return [ResultPO: filteredOrders]
}
def 'test order filtering'() {
expect:
buildResult(str1, str2) == [ResultPO: [[OrderNumber: '12345_00001', Location: 'US', Customer: 'ABC']]]
}
}

Preparing JSON array of Objects from multiple array list

I am very new to the Groovy scripts and would like to build a JSON output from the below JSON input. Kindly help!
My JSON input looks like this:
{
"id":"1222",
"storageNode": {
"uuid": "22255566336",
"properties": {
"BuinessUnit": [
"Light",
"Fan",
"Watch"
],
"Contact": [
"abc#gmail.com",
"fhh#gmail.com"
],
"Location": [
"Banglore",
"Surat",
"Pune"
]
}
}
}
Expected Output:
[
{
"BuinessUnit": "Light",
"Contact": "abc#gmail.com",
"Location": "Banglore"
},
{
"BuinessUnit": "Fan",
"Contact": "fhh#gmail.com",
"Location": "Surat"
},
{
"BuinessUnit": "Watch",
"Contact": "",
"Location": "Pune"
}
]
Please note that in case any array is not matching the value count that will always be the last one and in that case, a blank value ("") has to be populated. The "BusinessUnit" object can be referred for array size validation.
My code looks like this:
import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*;
def Message processData(Message message) {
//Body
def body = message.getBody(String.class);
def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(body)
String temp
def BU = list.storageNode.properties.get("BusinessUnit")
def builder = new JsonBuilder(
BU.collect {
[
BusinessUnit: it
]
}
)
message.setBody(builder.toPrettyString())
return message
}
It is only returning this:
[
{
"BusinessUnit": "Light"
},
{
"BusinessUnit": "Fan"
},
{
"BusinessUnit": "Watch"
}
]
Now how will I add other parts to it? Please help!
I have come up with the following solution that converts source JSON string to the target JSON string:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def json = '''
{
"id":"1222",
"storageNode": {
"uuid": "22255566336",
"properties": {
"BusinessUnit": [
"Light",
"Fan",
"Watch"
],
"Contact": [
"abc#gmail.com",
"fhh#gmail.com"
],
"Location": [
"Banglore",
"Surat",
"Pune"
]
}
}
}
'''
println convert(json)
String convert(String json) {
def list = new JsonSlurper().parseText(json)
List<String> units = list.storageNode.properties.BusinessUnit
List<String> contacts = list.storageNode.properties.Contact
List<String> locations = list.storageNode.properties.Location
def result = []
units.eachWithIndex { unit, int index ->
result << [
BusinessUnit: unit,
Contact : contacts.size() > index ? contacts[index] : '',
Location : locations.size() > index ? locations[index] : '',
]
}
return new JsonBuilder(result).toPrettyString()
}
I've omitted the logic of getting string from the message and packaging transformed JSON into message.
I hope it will help you to move forward. Please let me know if you need further assistance here.
You can use the built-in Groovy facilities, like transpose():
import groovy.json.*
def json = new JsonSlurper().parseText '''{ "id":"1222", "storageNode": { "uuid": "22255566336", "properties": {
"BuinessUnit": [ "Light", "Fan", "Watch" ],
"Contact": [ "abc#gmail.com", "fhh#gmail.com" ],
"Location": [ "Banglore", "Surat", "Pune" ] } } }'''
def names = json.storageNode.properties*.key
def values = json.storageNode.properties*.value
int maxSize = values*.size().max()
// pad lists with trainiling spaces
values.each{ v -> ( maxSize - v.size() ).times{ v << '' } }
def result = values.transpose().collect{ tuple -> [ names, tuple ].transpose().collectEntries{ it } }
assert result.toString() == '[[BuinessUnit:Light, Contact:abc#gmail.com, Location:Banglore], [BuinessUnit:Fan, Contact:fhh#gmail.com, Location:Surat], [BuinessUnit:Watch, Contact:, Location:Pune]]'
This piece of code can process everything under storageNode.properties.

This is json file named as 'abc' . I want to access file after that i want to access values of a,b,c,d,e,f . How can I access in groovy language?

{
"Product": [{
"a": "e3ae148d8bc2c5fe366c38da"
},
{
"b": "d211c6e7ed5bd8b4e9316a74085"
},
{
"c": "74be4f1b3b0fa5af77287780"
},
{
"d": "89856f4f139a84c98fb98b8b39c32e2"
},
{
"e": "7bd784e7d3b8490ed614345989a5"
},
{
"f": "d169f6a4a932841b12bdf8ccded57"
}
]
}
Use JsonSlurper,
File file = new File('abc')
String fileContent = file.text
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(fileContent)
println result.Product[0].a //etc.
...

Groovy: How to parse the json specific key's value into list/array

I am new to groovy and trying
1) from the output of prettyPrint(toJson()), I am trying to get a list of values from a specific key inside an json array using groovy. Using the below JSON output from prettyPrint example below, I am trying to create a list which consists only the values of the name key.
My Code:
def string1 = jiraGetIssueTransitions(idOrKey: jira_id)
echo prettyPrint(toJson(string1.data))
def pretty = prettyPrint(toJson(string1.data))
def valid_strings = readJSON text: "${pretty}"
echo "valid_strings.name : ${valid_strings.name}"
Output of prettyPrint(toJson(string1.data))is below JSON:
{
"expand": "places",
"places": [
{
"id": 1,
"name": "Bulbasaur",
"type": {
"grass",
"poison"
}
},
{
"id": 2,
"name": "Ivysaur",
"type": {
"grass",
"poison"
}
}
}
Expected result
valid_strings.name : ["Bulbasaur", "Ivysaur"]
Current output
valid_strings.name : null
The pretty printed JSON content is invalid.
If the JSON is valid, then names can be accessed as follows:
import groovy.json.JsonSlurper
def text = """
{
"expand": "places",
"places": [{
"id": 1,
"name": "Bulbasaur",
"type": [
"grass",
"poison"
]
},
{
"id": 2,
"name": "Ivysaur",
"type": [
"grass",
"poison"
]
}
]
}
"""
def json = new JsonSlurper().parseText(text)
println(json.places*.name)
Basically, use spray the attribute lookup (i.e., *.name) on the appropriate object (i.e., json.places).
I've used something similar to print out elements within the response in ReadyAPI
import groovy.json.*
import groovy.util.*
def json='[
{ "message" : "Success",
"bookings" : [
{ "bookingId" : 60002172,
"bookingDate" : "1900-01-01T00:00:00" },
{ "bookingId" : 59935582,
"bookingDate" : "1900-01-01" },
{ "bookingId" : 53184048,
"bookingDate" : "2019-01-15",
"testId" : "12803798123",
"overallScore" : "PASS" },
{ "bookingId" : 53183765,
"bookingDate" : "2019-01-15T13:45:00" },
{ "bookingId" : 52783312,
"bookingDate" : "1900-01-01" }
]
}
]
def response = context.expand( json )
def parsedjson = new groovy.json.JsonSlurper().parseText(response)
log.info parsedjson
log.info " Count of records returned: " + parsedjson.size()
log.info " List of bookingIDs in this response: " + parsedjson.bookings*.bookingId

how to print json array in jsonobject when we will get element of jsonarrray at runtime

ArrayList al = new ArrayList();
//al[0] and al[1] are the json objects.
def json = new JsonBuilder()
json {
type "rel12"
total k
xyz ""
shows al[0],al[1]
emails ""
}
println json.toPrettyString()
i dont want to do the the hardcoding like al[0]. al[1].
but i need the output like
{
"type": "rel12",
"total": 2,
"xyz": "",
"shows": [
{
"extension": "zip",
"updateTime": 1477521104511
},
{
"extension": "zip",
"updateTime": 1477521104623
}
],
"emails": ""
}