How do you index two value in JSON arrays? - json

I am trying to find an array index of two matching values. I have my Groovy script below that is giving me the index of WhenWeighed and that works. Returns the correct Index. The part I am having difficulty figuring out is adding OpSeq to the indexing criteria.
What I'm trying to do is find the index of WhenWeighed and OpSeq. For Example, I want to find the index of WhenWeighed = BH and OpSeq = 30. In my below JSON this should be 4.
Can anyone help explain how you do this in Groovy?
JSON Used:
{
"BusinessUnit": "1111111",
"WorkOrder": 1111111,
"WeightEstimatesInq": [
{
"WhenWeighed": "BH",
"WhenWeighedDesc": "Before Heading Weight",
"TotalWeight": 900,
"Weight": 12,
"OpSeq": "10",
"AdditionalNotes": " ",
"TareWeight": " ",
"Effective Date": "null"
},
{
"WhenWeighed": "AH",
"WhenWeighedDesc": "After Heading Weight",
"TotalWeight": 987,
"Weight": 900,
"OpSeq": "10",
"AdditionalNotes": "Weighed Bin 10 5/17/2022",
"TareWeight": "87",
"Effective Date": "null"
},
{
"WhenWeighed": "BO",
"WhenWeighedDesc": "Before OSP Weight",
"TotalWeight": 900,
"Weight": 9,
"OpSeq": "50",
"AdditionalNotes": " ",
"TareWeight": " ",
"Effective Date": "null"
},
{
"WhenWeighed": "AO",
"WhenWeighedDesc": "After OSP Weight",
"TotalWeight": 1000,
"Weight": 750,
"OpSeq": "50",
"AdditionalNotes": " ",
"TareWeight": "150",
"Effective Date": "null"
},
{
"WhenWeighed": "BH",
"WhenWeighedDesc": "Before Heading Weight",
"TotalWeight": 720,
"Weight": 700,
"OpSeq": "30",
"AdditionalNotes": "Weighed Bin 30 5/17/2022",
"TareWeight": "20",
"Effective Date": "null"
}
],
"status": "SUCCESS",
"startTimestamp": "2022-05-17T12:27:49.302-0400",
"endTimestamp": "2022-05-17T12:27:50.279-0400",
"serverExecutionSeconds": 0.977
}
Groovy Used:
// Read Input Values
String aWhenWeighedUDC = aInputMap.WhenWeighedUDC ?: " "
String aInputJson = aInputMap.InputJson ?: "{}"
// Initialize Output Values
def error = " "
def rowNumber = 0
def lastRowNumber = 1
// Parse JSON
def json = new JsonSlurper().parseText( aInputJson )
// Determine Row Numbers
def rowset = json?.WeightEstimatesInq
if ( rowset ) {
rowNumber = rowset*.WhenWeighed.indexOf( aWhenWeighedUDC ) + 1
lastRowNumber = rowset.size()
}

If you know that WeightEstimatesInq is always going to be the key for the list of items, you can do something like this:
json["WeightEstimatesInq"].findIndexOf {
it["WhenWeighed"] == "BH" && it["OpSeq"] == "30"
}
which will yield 4. You can add more criteria by && it.
Note that this has the potential to return -1 if nothing matches your criteria.

Related

How to remove brackets from JSON?

I have a groovy script that I want to return userDefinedErrorText. The issue I am having is that when parse my JSON I am having my failedForm variable equal [Failed] instead of "Failed".
If I remove the first pair of [] from my JSON input, I get the correct "Failed".
Is there a way to remove [] from the input JSON?
My Groovy
def json = new JsonSlurper().parseText( aInputJson )
failedForm = json?.userDefinedErrorText
if( failedForm == "Failed" ) {
resultMessage = "false"
}
JSON
[
{
"step": "abcd",
"message": {
"ServiceRequest: abc": {
"App Stack Form Exception": {
"Expecting Form": "P",
"Resulting Form": "P"
},
"JAS Response": {
"fs_P": {
"title": "I",
"data": {},
"errors": [
{
"CODE": "799L",
"TITLE": "Error: Invalid Long Address Number",
"ERRORCONTROL": "15",
"DESC": "CAUSE . . . . The long address number entered is not found in the Address Book\\u000a Master file (F0101).\\u000aRESOLUTION. . Enter a valid long address number.",
"MOBILE": "The long address number entered is not found in the Address Book\\u000a Master file (F0101)."
}
],
"warnings": []
},
"stackId": 12,
"stateId": 5,
"rid": "8f4",
"currentApp": "P",
"timeStamp": "2022-04-22:11.25.03",
"sysErrors": []
}
}
},
"timeStamp": "2022-04-22T11:25:03.235-0400",
"userDefinedErrorText": "Failed"
}
]
The issue I am having is that when parse my JSON I am having my
failedForm variable equal [Failed] instead of "Failed".
The following should work:
String jsonString = '''
[
{
"step": "abcd",
"message": {
"ServiceRequest: abc": {
"App Stack Form Exception": {
"Expecting Form": "P",
"Resulting Form": "P"
},
"JAS Response": {
"fs_P": {
"title": "I",
"data": {},
"errors": [
{
"CODE": "799L",
"TITLE": "Error: Invalid Long Address Number",
"ERRORCONTROL": "15",
"DESC": "CAUSE . . . . The long address number entered is not found in the Address Book\\\\u000a Master file (F0101).\\\\u000aRESOLUTION. . Enter a valid long address number.",
"MOBILE": "The long address number entered is not found in the Address Book\\\\u000a Master file (F0101)."
}
],
"warnings": []
},
"stackId": 12,
"stateId": 5,
"rid": "8f4",
"currentApp": "P",
"timeStamp": "2022-04-22:11.25.03",
"sysErrors": []
}
}
},
"timeStamp": "2022-04-22T11:25:03.235-0400",
"userDefinedErrorText": "Failed"
}
]'''
def json = new JsonSlurper().parseText(jsonString)
String value = json[0].userDefinedErrorText
assert value == 'Failed'

I need to split json data

I want to modify the current JSON file with the following change:
I want to edit the "Vs" column and split that data into two columns. I want it to be split into two columns named team 1 and team 2 respectively by splitting data after 'vs'.
How should I do that using python script?
Input: JSON data (this is sample data.)
[
{
"Match No": "1",
"Date": "17-10-21",
"Vs": "Sri Lanka vs Ireland",
"Rounds": "1st",
"Group": "Group A"
},
Required Output: JSON data
[
{
"Match No": "1",
"Date": "17-10-21",
"Team1": "Sri Lanka",
"Team2": "Ireland",
"Rounds": "1st",
"Group": "Group A"
},
So, I used the library json to serialize your input. THen you only need to loop over each object in the json array and create a new json object from the data. I hope you understand the principal.
import json
input = """
[
{
"Match No": "1",
"Date": "17-10-21",
"Vs": "Sri Lanka vs Ireland",
"Rounds": "1st",
"Group": "Group A"
}
]
"""
result = json.loads("""
[
]
""")
for o in json.loads(input):
teams = o["Vs"].split(" vs ")
result.append({
"Match No": o["Match No"],
"Date": o["Date"],
"Team 1": teams[0],
"Team 2": teams[1],
"Rounds": o["Rounds"],
"Group": o["Group"]
})
print(result)

Groovy Collect values from nested json arrays

I am trying to map a nested json into a flat file but have an issue referencing between different arrays.
I get it working for each array separately but can't figure out how to properly reference the parent ids to be included. I tried working with indexes and copying the event.id and event.lots.id on the pricings objects but that got really messy.
Maybe I am just on the wrong track or didn't have the right idea on how this might work.
Code
def body = message.getBody(String.class)
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText(body)
def i_events = object.events
def i_lots = object.events.lots
def i_pricing = object.events.lots.pricings
def o_values = i_pricing.flatten().collect {"(" + "'" + i_events.collect{it.id}[0] + "'" + "," + "'" + i_lots.collect{it.id}[1] + "'" + "," + "'" + it.id + "'" + "," + "'" +it.name + "'" + ")" }.join(',')
//just using print for testing
println o_values
Result
('event_id1','[id A, id B]','p id1','TEST 1'),('event_id1','[id A, id B]','p id2','TEST 2')
Expected Result
('event_id1','id3','p id1','TEST 1'),('event_id1','id A','p id2','TEST 2')
Sample input
{
"events": [
{
"id": "event_id1",
"name": "Test Event 01",
"to": "2021-08-27T02:30:00.000Z",
"from": "2021-08-26T16:15:00.000Z",
"parkingTo": "2021-08-27T02:30:00.000Z",
"parkingFrom": "2021-08-26T14:15:00.000Z",
"landmarkId": "111",
"slug": "test-event1",
"live": true,
"lots": [
{
"id": "id1",
"name": "Lot 1",
"pricings": []
},
{
"id": "id2",
"name": "Lot 2",
"pricings": []
},
{
"id": "id3",
"name": "Lot3",
"pricings": [
{
"id": "p id1",
"name": "TEST 1"
}
]
}
]
},
{
"id": "event_id2",
"name": "Test Event 2",
"to": "2020-08-31T17:00:00.000Z",
"from": "2020-08-31T14:00:00.000Z",
"parkingTo": "2020-09-01T08:45:00.000Z",
"parkingFrom": "2020-08-31T12:45:00.000Z",
"landmarkId": "111",
"slug": "test-event2",
"live": true,
"lots": [
{
"id": "id A",
"name": "lot A",
"pricings": [
{
"id": "p id2",
"name": "TEST 2"
}
]
},
{
"id": "id B",
"name": "lot B",
"pricings": []
}
]
}
],
"meta": {
"total": 2,
"firstElement": 0,
"lastElement": 2
}
}
Something like this should work (it's hard to say, as your example input seems different to your expected output)
I added a quote method for if the values contain a ', you will need to think if you need this, and how you're going to escape things
def escape(String s) {
"'${s.replaceAll("'", "\\\\'")}'"
}
def output = new JsonSlurper().parseText(body).events.collectMany { event ->
event.lots.collectMany { lot ->
lot.pricings.collect { pricing ->
"(${escape(event.id)}, ${escape(lot.id)}, ${escape(pricing.id)}, ${escape(pricing.name)})"
}
}
}.join(',')

Laravel querybuilder distinct function not working in search

I tried putting distinct() in my query but when i get the results in my frontend and in the api, I still get duplicate records. Does anyone know why distinct is not working in my code?
My code
$result = DB::connection('mysql2')
->table('xp_pn_ura_transactions')
->whereRaw(DB::raw("CONCAT(block, ' ', street,' ',project_name,' ', postal_code,'')LIKE '%$request->projectname%' order by STR_TO_DATE(sale_date, '%d-%M-%Y') asc"))
->limit($request->limit)
->distinct()
->get();
return \Response::json(array(
//'total_count' => $count,
'result' => $result,
));
Front end result
My response, I only get the first two objects that duplicates
{
"id": 228686,
"transtype": "RESI",
"project_name": "WATERFRONT WAVES",
"unitname": "08-06 ",
"block": "760",
"street": "Bedok Reservoir Road ",
"level": "08",
"stack": "06 ",
"no_of_units": "1",
"area": "147",
"type_of_area": "Strata",
"transacted_price": "1300500",
"nettprice": "-",
"unitprice_psm": "8847",
"unitprice_psf": "822",
"sale_date": "20-JAN-2008",
"contract_date": " ",
"property_type": "Condominium",
"tenure": "99 Yrs From 31/10/2007",
"completion_date": "Uncompleted",
"type_of_sale": "New Sale",
"purchaser_address_indicator": "Private",
"postal_district": "16",
"postal_sector": "47",
"postal_code": "479245",
"planning_region": "East Region",
"planning_area": "Bedok",
"update_time": "2019-12-09 17:14:35"
},
{
"id": 224686,
"transtype": "RESI",
"project_name": "WATERFRONT WAVES",
"unitname": "08-06 ",
"block": "760",
"street": "Bedok Reservoir Road ",
"level": "08",
"stack": "06 ",
"no_of_units": "1",
"area": "147",
"type_of_area": "Strata",
"transacted_price": "1300500",
"nettprice": "-",
"unitprice_psm": "8847",
"unitprice_psf": "822",
"sale_date": "20-JAN-2008",
"contract_date": " ",
"property_type": "Condominium",
"tenure": "99 Yrs From 31/10/2007",
"completion_date": "Uncompleted",
"type_of_sale": "New Sale",
"purchaser_address_indicator": "Private",
"postal_district": "16",
"postal_sector": "47",
"postal_code": "479245",
"planning_region": "East Region",
"planning_area": "Bedok",
"update_time": "2019-12-09 17:11:57"
}
They got different id but same records, is there a way to ignore the id and get the other fields?
You need to select the field that you need to distinct, or it will distinct all the fields that you selected:
So according to your post, the id and updated_time are not duplicated, you don't need to select it out.
Try something like this:
$result = DB::connection('mysql2')
->table('xp_pn_ura_transactions')
->whereRaw(DB::raw("CONCAT(block, ' ', street,' ',project_name,' ', postal_code,'')LIKE '%$request->projectname%' order by STR_TO_DATE(sale_date, '%d-%M-%Y') asc"))
->limit($request->limit)
# select the fields which is duplicated.(In your post, select the field without id and updated_time)
->select("transtype",
"project_name",
"unitname",
"block",
"street",
"level",
"stack",
"no_of_units",
"area",
"type_of_area",
"transacted_price",
"nettprice",
"unitprice_psm",
"unitprice_psf",
"sale_date",
"contract_date",
"property_type",
"tenure",
"completion_date",
"type_of_sale",
"purchaser_address_indicator",
"postal_district",
"postal_sector",
"postal_code",
"planning_region",
"planning_area")
->distinct()
->get();
if you need to select the fields not duplicated, you can use groupBy() instead of distinct()

Parsing a json using Angular js

{
"statusCode": "000",
"statusMessage": "Record Successfully Fetched",
"dsStatusCode": "000",
"dsStatusMessage": "Record Successfully Fetched",
"businessInput": null,
"businessOutput": {
"systemCircleId": "2",
"category": [
{
"categoryId": "abcs",
"sys": "5ID",
"displayName": "National Roaming Recharge",
"packsList": [
{
"amount": "79",
"benefits": "dsdsdsds",
"packId": "1344",
"processingFees": "70.3",
"serviceTax": "8.7",
"validity": "30 Days",
"volume": "0.0",
"isTop5": "no",
"fileName": "null"
},
{
"amount": "188",
"benefits": "Roaming Tariff - Incoming Free, Outgoing local # 80p/min, STD #1.15Rs/min with Talk Time 120 in main A/c",
"packId": "1263",
"fess": "47.3",
"serviceTax": "20.7",
"validity": "28 Days",
"volume": "0.0",
"isTop5": "no",
"fileName": "null"
},
{
"amount": "306",
"benefits": "FTT 306 with Roaming Tariff - Incoming Free, Outgoing local # 80p/min, STD #1.15Rs/min",
"packId": "1290",
"processingFees": "0",
"serviceTax": "33.7",
"validity": "28 Days",
"volume": "0.0",
"isTop5": "no",
"fileName": "null"
}
]
}
]
}
}
I want to parse this json to filter packlist for each category id using angularjs
assign a variable to the JSON you have. and use scope.$eval on the variable
Example
var jsonVar = { "statusCode": "000",
"statusMessage": "Record Successfully Fetched",
"dsStatusCode": "000",
"dsStatusMessage": "Record Successfully Fetched",
"businessInput": null
}
scope.$eval(jsonVar) // this gives the object on which you can do the ng-repeat
if you still have problems. Try using JSON.stringify(jsonVar) and then perform a scope.$eval on the this.
var jsonString = JSON.stringify(jsonVar);
scope.$eval(jsonString);// This returns a object too