Hello I wanted to ask how to retrieve the last value in a jsonPath
{
"testing": [
{
"transactionId": "5a99dcf84b7f633a5489805d",
"trackingId": "555112",
"tn": "6095555112",
"customerName": "John",
"customerLastName": "Chan"
},
{
"transactionId": "5a99dd3f4b7f633a54898068",
"tn": "6095555112",
"trackingId": "555112",
"customerName": "Amanda",
"customerLastName": "Brown"
}
]
}
My Java code Sample line
System.out.println("response.prettyPrint() = " + response.jsonPath().getString("testing.transactionId"));
Output
response.prettyPrint() = 5a99dcf84b7f633a5489805d,5a99dcf84b7f633a5489805d
Right now it is printing all transactionIds. It should be only pulling the latest one meaning the bottom one where transactionId = "5a99dd3f4b7f633a54898068"
If a new value come in (through back end logic, will add another set of values into this). How can I write a line that will pull the latest values set?
Example
{
"testing": [
{
"transactionId": "5a99dcf84b7f633a5489805d",
"trackingId": "555112",
"tn": "6095555112",
"customerName": "John",
"customerLastName": "Chan"
},
{
"transactionId": "5a99dd3f4b7f633a54898068",
"tn": "6095555112",
"trackingId": "555112",
"customerName": "Amanda",
"customerLastName": "Brown"
},
{
"transactionId": "newID",
"tn": "6095555112",
"trackingId": "555112",
"customerName": "Amanda",
"customerLastName": "Brown"
},
]
}
Now that a new dataset has been stored, How will I write a java code that would pull the transactionId "NewID"?
I don't want to hardcode and write something like ".transactionId[0]" [1] or [2]
Well instead of using getString you can use getList
For e.g
List<String> strList = response.jsonPath().getList("testing.transactionId");
System.out.println("last value is " + strList.get(strList.size()-1))
I hope this helps. I don't know the exact code but I know in an array you can get the last item like...
ARRAY.get(ARRAY.size()-1)
I am not sure how to properly implement that in your JSON array but I hope this sends you in the right direction.
With the Rest assured if you want to get the last item from array, you can use:
.extract()
.path("items[-1].value");
Related
I have a Json object like this in my Postgres DB:
{
"emails": [
{
"email": {
"id": "e8dc927f-679d-496b-85fb-465edf35c676",
"value": "hello#gmail.com"
}
},
{
"email": {
"id": "1b78758a-abc4-46ef-9de9-c999a0c8c418",
"value": "hello1#gmail.com"
}
}
],
"lastName": {
"id": "718109fd-2d00-475a-829a-c8af9a7f0067",
"value": "lastName"
},
"firstName": {
"id": "6c46a5b3-6f89-4692-a214-4943de22018d",
"value": "firstName"
},
}
And so on big json with around 1000 elements, now I want to parse and get the first 500 elements from json and make another json. what I mean by element here is anything which has Id is a element. For example firstName , LastName, email, email are the elements not the emails. I tried Jackson api but couldn't find a way how to count the elements and make a json exactly like above and return. and when I do any modifications in the first 500 elements I should save the Json with edits. Any help is much appreciated. I even tried postgres array_agg(e) function but that is only accepting only array.
Apologies if this is a duplicate post. I am trying to find a string in the following array response basing on conditions specified.
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/2016/drivers.json",
"limit": "30",
"offset": "0",
"total": "24",
"DriverTable": {
"season": "2016",
"Drivers": [
{
"driverId": "alonso",
"permanentNumber": "14",
"code": "ALO",
"url": "http://en.wikipedia.org/wiki/Fernando_Alonso",
"givenName": "Fernando",
"familyName": "Alonso",
"dateOfBirth": "1981-07-29",
"nationality": "Spanish"
},
{
"driverId": "bottas",
"permanentNumber": "77",
"code": "BOT",
"url": "http://en.wikipedia.org/wiki/Valtteri_Bottas",
"givenName": "Valtteri",
"familyName": "Bottas",
"dateOfBirth": "1989-08-28",
"nationality": "Finnish"
},
{
"driverId": "button",
"permanentNumber": "22",
"code": "BUT",
"url": "http://en.wikipedia.org/wiki/Jenson_Button",
"givenName": "Jenson",
"familyName": "Button",
"dateOfBirth": "1980-01-19",
"nationality": "British"
}
]
}
}
}
1) I would like to find the permanent number of driverId "alonso" assuming that it doesn't come first always in each request. i.e each time the request is made the arrays reshuffle. the logic here would be to get the array count of the driverId alonso and insert that into the query below
"MRData.DriverTable.Drivers[insert the array count of alonso here].permanentNumber"
2) I would like to get the permanent numbers that are less than 20. I would also like to get the driverIds of the drivers whose permanent numbers are less than 20.
thanks a lot for viewing!
Try to build the Classes "MRData" and "Driver" with all necessary parameters.
and let org.json or GSON do the magic. You should really look at How to parse JSON in Java as Lars mentioned.
got that sorted!
answer to my first question-
public void extraResponseWithInRange(String url) {
Response response = given().when().get(url);
List<Map<String, String>> responseFromArray = JsonPath.parse(response.asString()).read("$.MRData.DriverTable.Drivers[?(#.driverId== 'alonso')]");
for (Map<String, String> rfa : responseFromArray) {
assertThat(rfa.get("permanentNumber"), equalToIgnoringCase("14"));
answer to my second question-
List<Map<String,String>> driversBetween=JsonPath.parse(response.asString()).read("$.MRData.DriverTable.Drivers[?(#.permanentNumber > '0' && #.permanentNumber <'20')]");
for(Map<String,String> dbsmall: driversBetween){
System.out.println(dbsmall.get("permanentNumber"));
}
please let me know if i could write this in a better way.
thanks a lot!
Either marshall the data into a POJO, and check the values of the fields there, or use something like [JSONPath][1].
int permanentNumber = JSONPath.read(json, "$..Drivers[?(#.driverId == 'alonso')].permanentNumber");
Disclaimer, I don't have an environment currently to run this, but their docs are pretty good.
I've recently taken up Jayway JsonPath and I've had trouble with how the inpath filtering works.
So my JSON looks like this:
At the top I have shareables. These shareables have an array called user, which contains an ID and a name, and they also contain an item called dataset, which can contain any json.
These shareables can exist within the dataset as well.
My working JSON looks like this:
{
"shareable": {
"user": [
{
"ID": 1,
"Name": "Bob"
},
{
"ID": 2,
"Name": "Charles"
}
],
"dataSet": [
{
"insulinMeasurement":
{
"timestamp": "Tuesday Morning",
"measurement": 174,
"unit": "pmol/L"
}
},
{
"insulinMeasurement":
{
"timestamp": "Tuesday Noon",
"measurement": 80,
"unit": "pmol/L"
}
},
{ "shareable": {
"user": [
{
"ID": 3,
"Name": "Jim"
}
],
"dataSet": [
{
"insulinMeasurement":
{
"timestamp": "Tuesday Evening",
"measurement": 130,
"unit": "pmol/L"
}
}
]
}
},
{ "unshareable": {
"user": [
{
"ID": 2,
"Name": "Bob"
}
],
"dataSet": [
{
"insulinMeasurement":
{
"timestamp": "Tuesday Night",
"measurement": 130,
"unit": "pmol/L"
}
}
]
}
}
]
}
}
So what I want is, all shareables that have a user with a certain ID. So I figured the path I would use would look like this:
$..shareable[ ?(#.user[*].ID == 1 )]
which here has a hardcoded ID. This returns nothing while
$..shareable[ ?(#.user[0].ID == 1 )]
returns any shareable where the first ID is 1.
I also tried something along the lines of
$..shareable[ ?(#.user[?(#.ID == 1)]
which I figure should return any shareable that has a user with an ID of 1.
Am I going about this the wrong way? Do I need to somehow iterate through the user objects that exist?
Well, I figured it out, so if anyone stumbles across this, the query should look as follows:
$..shareable[?( " + user + " in #.user[*].ID )]
where user is just the int of the userId. Basically the right hand side creates a list of all IDs that shareable contains, and checks if the requested ID exists therein.
I have a table called Group and it will have records like:
{
"id": "UniqueID1",
"name": "Ranjeeth",
"emailIdMappings": [
{
"emailId": "r.pt#r.com",
"userId": 324
},
{
"emailId": "r1.pt#r.com",
"userId": 325
}
]
},
{
"id": "UniqueID2",
"name": "Ranjeeth",
"emailIdMappings": [
{
"emailId": "r1.pt#r.com",
"userId": 325
},
{
"emailId": "r2.pt#r.com",
"userId": 326
}
]
}
I need to query and get result if emailId contains the input string.
I have reached so far and I am not able to get the result
AttributeValue attributeValue = new AttributeValue("r.pt#r.com");
Condition containsCondition = new Condition()
.withComparisonOperator(ComparisonOperator.CONTAINS)
.withAttributeValueList(attributeValue);
Map<String, Condition> conditions = newHashMap();
conditions.put("emailIdMappings.emailId", containsCondition);
ScanRequest scanRequest = new ScanRequest()
.withTableName("Group")
.withScanFilter(conditions);
amazonDynamoDB.scan(scanRequest)
dynamoDBMapper.marshallIntoObjects(Group.class, scanResult.getItems());
For the above code I am expecting record with id UniqueID1, but it's empty. If you pass "r1.pt#r.com" then you should get both records.
sdk used is com.amazonaws:aws-java-sdk-dynamodb:1.11.155
I tried posting the question in aws forum which didn't help much.
As you have List of Objects which has two attributes in a object (i.e. emailId and userId), you need to provide both values in order to match the item.
The CONTAINS function will not be able to match the item if the object has two attributes and only one attribute value mentioned in the filter expression.
Otherwise, you need to provide the occurrence (i.e. index) of the list to match the item.
Example:-
emailIdMappings[0].emailId = :emailIdVal
im trying to get count / total number of records from list api using Restassured.
Please share thoughts on how can we get it.
ex:
{
"final list": [
{
"id": 123,
"name": "sachin"
},
{
"id": 234,
"name": "sourav"
}
]
}
I am expecting total as 2 here. please suggest.
I got answer to my question.
here is the code for rest assured
expect().body("final_list.findall.size()",equalTo(2)).when().get("/list.json);
thanks
if you expect final_list to have 2 elements, you can use the hasSize() matcher:
expect().body("final_list", hasSize(2)).when().get("/list.json);
I found this in the list of matchers from the Matchers class Java doc:
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasSize(org.hamcrest.Matcher)
Yo can do the following:
jp = new JsonPath(response.asString());
String numFromsResponse = jp.get("final list.id.size()").toString();
You may use:
var json = {
"final list": [
{
"id": 123,
"name": "sachin"
},
{
"id": 234,
"name": "sourav"
}
]
}
and then
json["final list"].length