rest assured check the name is exist in the json response - java

Am new to rest assured.Using rest assured am trying to verify data detail is found or not.Here two data details present.Some times it will be 2 or 3 or 5
Am getting response as follows and using java
{
"queryPath": "/api/",
"nId": "f084f5ad24fcfaa9e9faea0",
"statusCode": 707
"statusMessage": "Success",
"results": {
"data": [
{
"id": "10248522500798",
"capabilities": [
"record",
"HDt"
],
"name": "errt2"
},
{
"id": "418143778",
"capabilities": [
"1record",
"HDy"
],
"name": "Livin"
}
]
}
}
code using
JsonPath jsonResponse = new JsonPath(response.asString());
ArrayList<String> list = new ArrayList<String>();
list = jsonResponse.get("results.data"); //
if (list.size() < 1 ) {
SpiceCheck.fail("data not found! " + list.size());
}
Rather than this i wwant to check the data name is null or not also.How can i do that rest assured.

Just so you know you are missing a comma after 707.
To verify that none of the names is null I would parse out the names as a list, then iterate over the names one by one and check that they aren't null.
List<String> names = from(response.asString()).getList("results.data.name");
for(String name : names){
if(name == null){
// error handling code here
}
}

Related

Transform JSON query filter into SQL?

I'm looking for a java library that can translate json input into SQL dynamically.
For example, the library could expect the following json data:
{
"rules": [
{
"field": "firstname",
"value": [
"John",
"Doe"
],
"operator": "in"
},
{
"rules": [
{
"field": "age",
"value": 18,
"operator": "EQUALS"
}
],
"condition": "AND"
}
]
}
And should then be able of translating this into a dynamic sql query:
SELECT * FROM persons where firstname IN ("John", "Doe") AND age = 18;
Is there any existing framework that I could build this upon?
I am not sure about library to get the expected output. But you can use the following code to write Java method.
Assuming that input will be JSON object.
JSONObject jo = (JSONObject) obj;
// getting fieldname and operator
String field= (String) jo.get("field");
String operator= (String) jo.get("operator");
//getting values
JSONArray ja = (JSONArray) jo.get("value");
// iterating values
Iterator itr2 = ja.iterator();
Then you can use above to write dynamic SQL query.

Karate - Compare multiple JSON objects schema

I am trying to validate a JSON which has multiple JSON objects nested.
example
Scenario: temp1
* def response1 =
"""
{
"productGroups": [
{
"dateLabel": "28 Aug, Wed",
"products": [
{
"id": 1439,
"product": "product 1"
},
{
"id": 1401,
"product": "product 2"
}
]
}
]
}
"""
* print response1.productGroups
Then match response1.productGroups[*] contains
"""
{
'dateLabel': #string,
'products': [
{
'id': #number,
'product': #string
}
]
}
"""
Getting the response as
reason: actual value does not contain expected
if I change the validate as
Then match response1.productGroups[0] contains
Getting the response as
reason: actual and expected arrays are not the same size - 2:1
What I wanted to do is verify the schema of "productGroups" object along with the inner objects of "products"
Please spend some time reading the docs, it is worth it: https://github.com/intuit/karate#schema-validation
* def product = { 'id': #number, 'product': #string }
Then match response1.productGroups[*] contains
"""
{
'dateLabel': #string,
'products': '#[] product'
}
"""

How to set nested JSON data to datatables?

I have a (nested) data structure containing objects and arrays. And trying to sent datatables but only one value displaying.
JSON data:
{
"data": [{
"name": "name1",
"value": "value1",
"list": [{
"sname": "sname1",
"svalue": "svalue1"
}, {
"sname": "sname2",
"svalue": "svalue2"
}]
}]
}
JSON data getting through URL by using Java.
jQuery code:
var pk = $("#pk").val();
console.log(pk);
url = "/register/search?id=" + pk;
console.log(url);
$('#largeTable').DataTable({
"ajax": url,
"bDestroy": true,
"columns": [{
"data": "name"
},
{
"data": "value"
},
{
"data": "list.1.sname"
},
{
"data": "list.1.svalue"
},
{
"data": null,
"defaultContent": editview
}
]
});
Here it is possible to display either first or second list values by using list.1 or list.0
But I want two values at a time.
If you used render or mRender you can do what you want with the object. For example you can traverse the array like in this example.
$('#largeTable').DataTable({
"columnDefs": [
{"targets": [0], "title":"name", "data":"name"},
{"targets": [1], "title":"value", "data":"value"},
{"targets": [2], "title":"list", "data":"list", "type":"html"
"render":function(data){
var listArray = data;
var listHtml = "";
for(var i=0;i<listArray.length;i++) {
listHtml += listArray[i].sname + " " + listArray[i].svalue + "<br>";
}
return listHtml;
},
}]
});
$.ajax({
"type":"GET",
"url":url,
"success":function(data,status) {
var jsonData = $.parseJSON(data);
$('#largeTable').dataTable().fnAddData(jsonData);
}
Your list in json data structure is an array. So, you should use
list.forEach(function(element) {
//console.log(element);
});
You could create an object and build JSON dynamically and set it to "columns" array.
Here is an example:
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';

updating json value of a nested json array in a json file | Java

I have this below json content in a file.
[
{
"prjId": 1,
"name" : "ABC",
"issueCounter": 7,
"issue": [
{
"id": 1,
"status" : "Closed",
"comment" : "blah blah blah",
"loggedBy": "shdkjdlsj"
},
{
"id": 2,
"status" : "Open",
"comment": "nothing",
"loggedBy": "xyz"
}
]
},
{
"prjId": 2,
"name" : "XYZ",
"issueCounter": 7,
"issue": [
{
"id": 3,
"status" : "Closed",
"comment": "jjjjjjjj",
"loggedBy": "klwm"
},
{
"id": 4,
"status" : "Closed",
"comment": "test test test",
"loggedBy": "NACK"
}
]
}]
I am able to parse this file and then traverse this json to get to the node where i wish to update. Upon reaching that point, i am confused on how to update it so that it would reflect on file on filesystem.
JSONParser parser = new JSONParser();
JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName));
JSONObject project=null;
for (Object rootEntry : rootArray)
{
project = (JSONObject) rootEntry;
if( 1 == (Long) project.get("prjId"))
{
JSONArray issueArray = (JSONArray) project.get("issue");
for (Object issueEntry : issueArray)
{
JSONObject issue = (JSONObject) issueEntry;
System.out.println((Long) issue.get("id"));
if(2==(Long) issue.get("id"))
{
//now update the "comment" attribute here.
System.out.println("updated the comment: "+trckParam.getComment());
}
}
}
I have just the json reader till this point so do I construct a String as-and-when I traverse the nodes and when i reach the point I need to update, I update it (and construct the remainder of the nodes in this json object, (not to break from the loop)) and then write the entire reconstructed string to same file? Or is there a better approach where I can traverse the JSONObject and once i update it, push the entire object onto a file without constructing a String of entire file.
I still need to figure out a way to take either of the approach. So any pointers or direction will be greatly helpful.

Get sub-array from JSON

I parsing some data from a json file. Here is my JSON File.
[
{
"topic": "Example1",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
},
{
"topic": "Example2",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Poster"
}
]
I can fetch and store data one by one. Like this one
JSONArray getContactsArray = new JSONArray(jsonObject.getString("contact"));
for(int a =0 ; a < getContactsArray.length(); a++)
{
JSONObject getJSonObj = (JSONObject)getContactsArray.get(a);
String Name = getJSonObj.getString("name");
}
1)Now, my question is there any way to get all name values for each array with single query.
2) Can I get all those values in an Array ?
Please correct me, if I am doing anything wrong. Thank you.
Iteration cannot be avoided here as org.json and other Json parsers as well provide random access to objects but not to their properties collectively (as a collection). So, you can't query something like "all name properties of all contact objects" unless you probably get a Json parser like Gson to unmarshall it that way.
But, that's too much to just avoid a for loop when you can definitely shorten the parse by making use of the appropriate API methods to avoid unnecessary object casts.
JSONArray contacts = jsonObject.getJSONArray("contact");
String[] contactNames = new String[contacts.length()];
for(int i = 0 ; i < contactNames.length; i++) {
contactNames[i] = contacts.getJSONObject(i).getString("name");
}
Better to use a json parser such as GSon or Jackson to marshall your json to a java object. Then you can write utitlity method in your java class to retrieve all the names in that object.
Try this:
Create JSONObject of your file and try to get array of all names and iterate it to get all values.
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = (String) i.next();
j += 1;
}
return names;
}

Categories