Accessing jsonpath elements with nested objects - rest-assured

I am looking to extract certain values from a JSON path of arrays and objects and use these values for further processing and am struggling with accessing those elements. Here is the JSON response:
[
{
"od_pair":"7015400:8727100",
"buckets":[
{
"bucket":"C00",
"original":2,
"available":2
},
{
"bucket":"A01",
"original":76,
"available":0
},
{
"bucket":"B01",
"original":672,
"available":480
}
]
},
{
"od_pair":"7015400:8814001",
"buckets":[
{
"bucket":"C00",
"original":2,
"available":2
},
{
"bucket":"A01",
"original":40,
"available":40
},
{
"bucket":"B01",
"original":672,
"available":672
},
{
"bucket":"B03",
"original":632,
"available":632
},
{
"bucket":"B05",
"original":558,
"available":558
}
]
}
]
I tried accessing the root elements with $ but I could not get further with it.
Here is the test method that I have written. I want to extract the value for od_pair and within each od_pair, I need to be able to retrieve the bucket codes and their available numbers.
public static void updateBuckets(String ServiceName, String DateOfJourney) throws Exception {
File jsonExample = new File(System.getProperty("user.dir"), "\\LogAvResponse\\LogAvResponse.json");
JsonPath jsonPath = new JsonPath(jsonExample);
List<Object> LegList = jsonPath.getList("$");
// List<HashMap<String, String>> jsonObjectsInArray = jsonPath.getList("$");
int NoofLegs = LegList.size();
System.out.println("No of legs :" + NoofLegs);
for (int j = 0; j <= NoofLegs; j++)
// for (HashMap<String, String> jsonObject : jsonObjectsInArray) {
{
String OD_Pair = jsonPath.param("j", j).getString("[j].od_pair");
// String OD_Pair = jsonObject.get("od_pair");
System.out.println("OD Pair: " + OD_Pair);
List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");
int NoOfBuckets = BucketsList.size();
// System.out.println("OD Pair: " + OD_Pair);
System.out.println("no of Buckets: " + NoOfBuckets);
for (int i = 0; i < NoOfBuckets; i++) {
String BucketCode = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].bucket");
String Available = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].available");
int BucketCodeColumn = XLUtils.getBucketCodeColumn(BucketCode);
int ServiceRow = XLUtils.getServiceRow(ServiceName, DateOfJourney, OD_Pair);
System.out.println("Row of " + ServiceName + ":" + DateOfJourney + "is:" + ServiceRow);
System.out.println("Bucket Code column of " + BucketCode + " is: " + BucketCodeColumn);
XLUtils.updateAvailability(ServiceRow, BucketCodeColumn, Available);
}
}
}
}
This is the error I see:
Caused by:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup
failed:
Script1.groovy: 1: unexpected token: [ # line 1, column 27.
restAssuredJsonRootObject.[j].od_pair
Can someone help me please?

I would suggest parsing your JSON into Java classes to ease the processing.
How to do that?
First, we need to create Java classes which will represent the JSON you provided.
Let's analyze the JSON.
Starts with an array. The array contains multiple JSON Object. These objects contain od_pair value and array of objects called buckets.
Let's create a class (you can name it whatever you want) Pair
public class Pair {
public String od_pair; //this name is important because it corresponds with the json element's name!
public List<BucketObject> buckets; //same here!
}
This class represents a single JSON Object in the main Array. It contains od_pair value AND nested JSON Array but in Java representation -> List of BucketObject classes. Let's create BucketObject class:
public class BucketObject { //this name is NOT importnat
public String bucket; //names are important
public int original;
public int available;
}
We have only 3 values in each of the objects.
Now, it's time to parse JSON into the written classes.
JsonPath path = JsonPath.from(json);
Pair[] pairs = path.getObject("$", Pair[].class);
Remember that Pair is a single JSON Object. That's why we start parsing from the root represented by dollar sign $ and we declare that JSON should be parsed into an ARRAY of Pair objects!
Now, processing will be much simpler!
I am not sure what do you need, but I will show you an example of how to get data from the buckets based on od_pair field and you should be able to figure out the rest of the processing.
So, we have the array of Pair class: Pair[] pairs;
Now, we want to get 1 Pair object based on od_pair value.
public static Pair getPairBasedOnOdPairValue(Pair[] pairs, String odPairValue) {
for (Pair pair : pairs) {
if (pair.od_pair.equals(odPairValue)) return pair;
}
throw new NoSuchElementException();
}
Now, we have the Pair object. We can access buckets for this object using
List<BucketObject> buckets = pair.buckets;
The rest of the processing is iterating over List<BucketObject> and getting desired values.
Hope it helps!

OP asked me to advise on how to fix his code, hence the second answer.
Let's analyze the code you provided:
public static void updateBuckets(String ServiceName, String DateOfJourney) throws Exception {
File jsonExample = new File(System.getProperty("user.dir"), "\\LogAvResponse\\LogAvResponse.json");
JsonPath jsonPath = new JsonPath(jsonExample);
List<Object> LegList = jsonPath.getList("$");
// List<HashMap<String, String>> jsonObjectsInArray = jsonPath.getList("$");
int NoofLegs = LegList.size();
System.out.println("No of legs :" + NoofLegs);
for (int j = 0; j <= NoofLegs; j++)
// for (HashMap<String, String> jsonObject : jsonObjectsInArray) {
{
String OD_Pair = jsonPath.param("j", j).getString("[j].od_pair");
// String OD_Pair = jsonObject.get("od_pair");
System.out.println("OD Pair: " + OD_Pair);
List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");
int NoOfBuckets = BucketsList.size();
// System.out.println("OD Pair: " + OD_Pair);
System.out.println("no of Buckets: " + NoOfBuckets);
for (int i = 0; i < NoOfBuckets; i++) {
String BucketCode = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].bucket");
String Available = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].available");
int BucketCodeColumn = XLUtils.getBucketCodeColumn(BucketCode);
int ServiceRow = XLUtils.getServiceRow(ServiceName, DateOfJourney, OD_Pair);
System.out.println("Row of " + ServiceName + ":" + DateOfJourney + "is:" + ServiceRow);
System.out.println("Bucket Code column of " + BucketCode + " is: " + BucketCodeColumn);
XLUtils.updateAvailability(ServiceRow, BucketCodeColumn, Available);
}
}
}
I am not using compilator right now, so I can miss a few things.
#1
First thing I can see is that you save the main array into the List<Object>
List<Object> LegList = jsonPath.getList("$");
Instead, you could save it to more understandable type, since Object is so generic, you have no idea what's inside it.
List<HashMap<String, Object>> LegList = jsonPath.getList("$");
#2
The for loop looks incorrect because of the evaluator
j <= NoofLegs;.
This will probably cause IndexArrayOutOfBoundsException or something similar. With the given code, if you have 4 legs, the for loop will try to process 5 legs which are incorrect.
#3
Similar to the #1, line where you save the bucket list
List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");
Could also be changed to List<HashMap<String, Object>> instead.
If you'd do that, you wouldn't need integer-based nested for loop.
You see, the HashMap<String, Object> is actually crucial to parse nested objects. The String is just a name like buckets or od_pair. It's the JSON representation. The second argument Object is different. RestAssured returns different types within the HashMap, that's why we use Object instead of String. Sometimes it's not String.
Example based on your JSON:
Collect buckets to List of HashMaps:
List<HashMap<String, Object>> bucketsList = jsonPath.param("j", j).getList("[j].buckets");
Each of the HashMap in the list is a representation of this:
{
"bucket":"C00",
"original":2,
"available":2
},
The Object in HashMap is either String or Integer in your case.
So, if you get element bucket from a HashMap you'll get its value.
Let's combine it with for loop for further clarification:
List<HashMap<String, Object>> bucketsList = jsonPath.param("j", j).getList("[j].buckets");
for (HashMap<String, Object> singleBucket : bucketsList) {
String firstValue = (String) singleBucket.get("bucket");
Integer secondValue = (Integer) singleBucket.get("original");
}

Looking at the error message, it looks like you are using rest-assured and that the JsonPath class is io.restassured.path.json.JsonPath from the rest-assured library.
I'm sure you're aware, but (perhaps for other readers) note that this is different from Jayway's json-path and is NOT the com.jayway.jsonpath.JsonPath class from that library.
Also be aware that, as mentioned in the documentation rest-assured uses the Groovy GPath syntax for manipulating/extracting JSON.
With that, I believe the following will extract what you need, i.e. od_pair and their corresponding buckets with available numbers:
Map<String, Map<String, Integer>> map = JsonPath.with(jsonString).get("collectEntries{entry -> [entry.od_pair, entry.buckets.collectEntries{bucketEntry -> [bucketEntry.bucket, bucketEntry.available]}]}");
where for each entry of the map, the key is the od_pair and the value is another map whose key is the bucket and value is the available number. The jsonString is the JSON you provided in the question.
You can iterate through the map to get what you want:
for(Map.Entry<String, Map<String, Integer>> entry : map.entrySet())
{
String od_pair = entry.getKey();
Map<String, Integer> bucketMap = entry.getValue();
for(Map.Entry<String, Integer> bucketEntry : bucketMap.entrySet())
{
String bucket = bucketEntry.getKey();
int available = bucketEntry.getValue();
}
}
Printing out the map you will get:
{7015400:8727100={C00=2, A01=0, B01=480}, 7015400:8814001={C00=2, A01=40, B01=672, B03=632, B05=558}}
Printing the map as JSON using Gson:
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(map));
you will get
{
"7015400:8727100": {
"C00": 2,
"A01": 0,
"B01": 480
},
"7015400:8814001": {
"C00": 2,
"A01": 40,
"B01": 672,
"B03": 632,
"B05": 558
}
}
For background, the String collectEntries{entry -> [entry.od_pair, entry.buckets.collectEntries{bucketEntry -> [bucketEntry.bucket, bucketEntry.available]}]}
is a Groovy closure that uses methods from the Groovy Collections API: Refer Collection, List and Map
Shout out to #Fenio for the pure Java solution above.

Related

The operator '[]=' isn't defined for the type 'String'

I'm getting an error in this code:
void main() {
List<String> wave(String str) {
List<String> results = [];
String newStr;
int i = 0;
for (String ltr in str.split('')) {
newStr = str;
if (ltr != ' ') {
newStr[i] = ltr.toUpperCase();
results.add(newStr);
}
i++;
}
return results;
}
print(wave(' gap '));
}
the error is at the line:
newStr[i] = ltr.toUpperCase;
Despite when I try print(newStr[i]); I don't get an error and the code is executed correctly!
In Dart String operation, operator[] returns a string. Which means, array[index] is used for getting the string in the index position. That is why you're getting that error, because you can't set at specific index using this operator[] in dart. See the documentation for details.
To replace at the specific index in dart, you can use replaceFirst(Pattern from, String to, [int startIndex = 0]) as the other answer mentioned. Or, you can use substring(int start, [int? end]) as follows:
if (ltr != ' ' && i < newStr.length) {
newStr = newStr.substring(0, i) + ltr.toUpperCase() + newStr.substring(i+1);
results.add(newStr);
}
To make the code bug free, I've added the checking of the value of i in it. You should add the checking to avoid out of bound access.
try to replace
newStr[i] = ltr.toUpperCase();
to
newStr = newStr.replaceFirst(ltr,ltr.toUpperCase(),i);
So the result will be [ Gap , gAp , gaP ]
Honestly, I don't know how char is defined in Dart, but I think accessing index of String is kind of getter, thus cannot be set to a new value.

How to create a function WordSplit(strArr) read the array of strings stored in strArr using dart

I have a simple exercise in Coderbyte, it just want to have a function that's WordSplit(strArr) read the array of strings stored in strArr, For example I have two elements like ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]
I just want to to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input.
For example: the first element can be split into two words: hello and cat because both of those words are in the dictionary.
So the program should return the two words that exist in the dictionary separated by a comma, as this result hello,cat .
I've made a recursive solution below. It checks if the string to be split starts with any word in the dictionary. If it exists, the function is called again using a substring with that first word removed.
This function only works up to the first word that isn't in the dictionary since you did not specify the expected behavior when the inputted word is not made up of words in the dictionary. You could make it throw an exception perhaps, but please specify your expectation.
void main() {
print(wordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
//hello,cat
}
String wordSplit(List<String> arg) {
String wordToSplit = arg[0];
String dict = arg[1];
List<String> parsedDict = arg[1].split(',');
for(String word in parsedDict) {
if(wordToSplit.startsWith(word)) {
//If the substring would be empty, don't do more recursion
if(word.length == wordToSplit.length) {
return word;
}
return word + ',' + wordSplit([wordToSplit.substring(word.length), dict]);
}
}
return wordToSplit;
}
#include <bits/stdc++.h>
using namespace std;
vector<string> converToWords(string dict) {
vector<string> res;
string s = "";
int n = dict.length();
for(int i=0; i<n; i++) {
if(dict[i] == ',') {
res.push_back(s);
s = "";
}
else s += dict[i];
}
res.push_back(s);
s = "";
return res;
}
string solve(string str[]) {
string result = "";
string word = str[0], dict = str[1];
int n = word.length();
vector<string> vs = converToWords(dict);
unordered_set<string> ust;
for(auto it: vs) ust.insert(it);
// for(auto i=ust.begin(); i!=ust.end(); i++){
// cout<<*i<<endl;
// }
string s = "";
for(int i=0; i<n; i++) {
s += word[i];
// cout<<s<<endl;
string temp = word.substr(i+1, n-(i+1));
// cout<<temp<<endl;
if(ust.find(s) != ust.end() && ust.find(temp) != ust.end()) {
cout<<s<<endl;
cout<<temp<<endl;
result += s+","+temp;
break;
}
temp = "";
}
return result;
}
int main() {
string arr[2];
cin>>arr[0]>>arr[1];
cout << solve(arr);
return 0;
}

Dart converting String to Array then compare two array

I'm trying to convert strings to arrays then compare two arrays. If the same value needs to remove from both array. Then finally merge two arrays and find array length. Below is my code
String first_name = "siva";
String second_name = "lovee";
List<String> firstnameArray=new List();
List<String> secondnameArray=new List();
firstnameArray = first_name.split('');
secondnameArray = second_name.split('');
var totalcount=0;
for (int i = 0; i < first_name.length; i++) {
for (int j = 0; j < second_name.length; j++) {
if (firstnameArray[i] == secondnameArray[j]) {
print(firstnameArray[i] + "" + " == " + secondnameArray[j]);
firstnameArray.removeAt(i);
secondnameArray.removeAt(i);
break;
}
}
}
var finalList = new List.from(firstnameArray)..addAll(secondnameArray);
print(finalList);
print(finalList.length);
But always getting this error Unsupported operation: Cannot remove from a fixed-length list can you help me how to fix this issue. Thanks.
Seems like what you are trying to do is to find the length of unique characters in given two strings. Well, the Set type is perfect for this use-case. Here's an example of what you can do:
void main() {
String first = 'abigail';
String second = 'allie';
var unique = '$first$second'.split('').toSet();
print(unique);
}
This would give you an output of:
{a, b, i, g, l, e}
On which you may perform functions like .toList(), or .where() or .length.
You can ensure that firstnameArray, secondnameArray is not a fixed-length list by initializing it as below:
var firstnameArray = new List<String>.from(first_name.split(''));
var secondnameArray= new List<String>.from(second_name.split(''));
Thereby declaring firstnameArray, secondnameArray to be a mutable copy of input.

Extracting last item from string in foreach loop

I'm working on matrix that contains the name of a class, but sometimes the class name is very long and I only need two last sections of name.
I have string containing some text, separated with '.', and I need to extract last two text.
For example:
string : af.bf.cf.df.ef
my needed value : df.ef
I wrote some code, but it's not working:
string[] split1 = "af.bf.cf.df.ef";
foreach (string item in split1)
{
string myvalue = item;
}
string[] list = "1.2.3.4.5".Split('.');
string last2 = list[ list.count - 2] + "." + list[ list.count - 1];

How to build params based on the length of the array?

function BuildParams(arr)
{
// arr is an Array
// how to build params based on the length of the array?
// for example when arr.Length is 3 then it should build the below:
var params = {
'items[0]' : arr[0],
'items[1]' : arr[1],
'items[2]' : arr[2]
},
return params;
}
Then I'd like to be able to send it to my ajax get:
var arr = ['Life', 'is', 'great'];
$.get('/ControllerName/ActionName', BuildParams(arr))
.done(function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
})
.fail(function(data) {
alert(data.responseText);
});
var result = {}
jQuery.each(['Life', 'is', 'great'], function(index, value){
result['items[' + index + ']'] = value;
});
jQuery.each:
A generic iterator function, which can be used to seamlessly iterate
over both objects and arrays. Arrays and array-like objects with a
length property (such as a function's arguments object) are iterated
by numeric index, from 0 to length-1. Other objects are iterated via
their named properties.
Just iterate over the array, adding each element in the array as a new property of a params object:
var params = {}; // start with an empty object
for(var i = 0; i < arr.length; i++) {
params["items[" + i + "]"] = arr[i];
}
return params; // return the populated params object
Change BuildParams(arr) to:
{items: arr}
jQuery will correctly serialize objects into query-strings, including objects with items that are arrays.

Resources