total / count items from list json response - java

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

Related

How to count particular pattern in a string?

we have some requests which have a lot of experiments. I just want to count the no experiments. If it's greater than some number then I will block those requests
{
"context": {
"requestId": "",
"locale": "",
"deviceId": "",
"currency": "",
"memberId": 0,
"cmsOrigin":,
"experiments": {
"forceByVariant":,
"forceByExperiment": [
{
"id": "test",
"variant": "A"
}
]
}
}
In this request, I just want to check how many id and variant inside the forceByExperiment. I have tried to do using regular expression but not able to do it. Anyone do it before similar thing.
I just split the string with variant and count them. Not sure good idea, but the end goal is to figure out that the request have a lot of experiments.
Using the circe library and Scala, here is an easy solution:
import io.circe._, io.circe.parser._
val jsonString = """{
"context": {
"requestId": "",
"locale": "",
"deviceId": "",
"currency": "",
"memberId": 0,
"cmsOrigin": "foo",
"experiments": {
"forceByVariant": [],
"forceByExperiment": [
{
"id": "test",
"variant": "A"
}
]
}
}
}"""
val parseResult = parse(jsonString)
val nElems = for {
json <- parse(jsonString)
array <- json.hcursor.downField("context").downField("experiments").downField("forceByExperiment").as[Seq[Json]]
} yield array.length
println(nElems) // Right(1)
If you really want to use regex, and if there is no id field in your json structure, you can use the following expression "id": "(\w+)" and count the number of match.
Example: https://regex101.com/r/GCeByw/1/

how to find the string in a Json array response in JAVA based on conditions

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.

How to pull the last jsonPath value in Java?

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");

Jayway JsonPath filtering with predicates

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.

Parse json response of rest API and delete certain jsonObjects - JAVA

I have a json file as below which I am getting as a response from rest API:
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [
{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}
]
}
I am trying to parse this in Java and to remove some unwanted json objects. Like I want the following string to be replaced by blank:
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item":
To achieve this I am trying the following approach:
String jsonStr = new String(Files.readAllBytes(Paths.get(inputFile)));
System.out.println(jsonStr);
jsonStr.replaceAll("link", "");
But it is not replacing the required string with blanks. Please help me in this.
string object is immutable , so basically if do you want to replace something
System.out.println(jsonStr.replaceAll("link", "")); this will print the replaced string but it will not affect the original string, however if you do this
jsonStr=jsonStr.replaceAll("link", "");
System.out.println(jsonStr); this will print the replaced string
First of all:
Your JSON is not validate. You're missing a closing curly bracket at the end of it.
{
"label": " MARA LEYZIN",
"ClassCode": "PROFESSIONAL",
"actvFlg": "A",
"name": "MARA LEYZIN",
"Typ": {
"label": "C_TYP_LU",
"TypCode": "PROFESSIONAL "
},
"Address": {
"link": [],
"firstRecord": 1,
"pageSize": 10,
"searchToken": "multi",
"item": [{
"label": "Address",
"addrTypFk": {
"label": "C_ADDRESS_TYPE_LU",
"addrTypCd": "INDUSTRY",
"addrTypDesc": "Industry"
}
}]
}
}
Second of all you should just change order of your commands to this:
jsonStr.replaceAll("link", "");
System.out.println(jsonStr);
Important addition:
And I would suggest you to use org.json library or even better JACKSON to parse JSON files.
Here's tutorial how to use jackson and it's my warmest suggestion.
You will save a lot of time and you can do whatever you like.

Categories