I'm now working with API calls currectly, so most the requests are done through ajax call. As you can expect, both the data sent to server and data received from server will be xml data. I've successfully able to dynamically construct the xml data during the sign up process and during post requests. By utilising JaxB, I've done the necessary steps in server.
Now I've to get the data as xml from server if a user needs to view a ceertain resource. Like before, I'm using jaxb to convert Java object into xml data and I'm getting the xml data in success function of Javascript. There are lot of examples and questions present on converting this xml data into user viewable form.
By my main goal is to make every function Dynamic, Consider now I'm going to show the list of users to admin, I can use these examples to convert my xml data into tables.
Display JSON Data in HTML Table
populate jquery data table with returned json data
If I'm doing like that, I've to manually write the same process with some modification based on table fields for every list view. This is a bad practise if I'm going to copy paste the same code with some modifications for 10 list views. I would like to make the xml to table conversion as a common function for any number of tables no matter how many fields are present in it.
I'm getting the xml data from server as String. So I've converted it to recognizable xmlData using following code.
var xmlData = jQuery.parseXML(data); //data is the xml String which I'm getting from server
//Converting xmlData into JSON Objects
var containerTag = myTag //I can get this from - document.getElementById("tableId").name
var output = new Array( );
var rawData = xmlData.getElementsByTagName(containerTag)[0];
var i, j, oneRecord, oneObject;
for (i = 0; i < rawData.childNodes.length; i++) {
if (rawData.childNodes[i].nodeType == 1) {
oneRecord = rawData.childNodes[i];
oneObject = output[output.length] = new Object( );
for (j = 0; j < oneRecord.childNodes.length; j++) {
if (oneRecord.childNodes[j].nodeType == 1) {
oneObject[oneRecord.childNodes[j].tagName] = oneRecord.childNodes[j].firstChild.nodeValue;
}
}
}
}
By displaying the data as console.log(output[0]); , I'm getting my real data. But I searched to use this information to populate it in table, most of them suggests to do it like
.fieldname1
.fieldname2
and so on which is not I'm expecting to. I've been learning Javascript now a days, but I dont know how to make the process common for all tables irrespective of no of fileds.
Note: I'm using jquery datatables.
Just a thought comes up in my head. Is it possible to just give the Json object to jquery datatables and it'll do the remaining process..?
For reference, this is my xml data
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<user>
<id>1</id>
<username>user1</username>
<email>email1</email>
<status>active</status>
</user>
<user>
<id>2</id>
<username>user2</username>
<email>email2</email>
<status>active</status>
</user>
<user>
<id>3</id>
<username>user3</username>
<email>email3</email>
<status>inactive</status>
</user>
</Users>
This is the Json object
Object { id: "1", username: "user1", email: "email1", status: "active" } //output[0]
Object { id: "2", username: "user2", email: "email2", status: "active" } //output[1]
Object { id: "3", username: "user3", email: "email3", status: "inactive" } //output[2]
As #epascarello said only a cleaner way is to create tr's dinamically based on the output array index and td's based on the keys from the output[i] -json. Using jquery an example should look like this.
var table = $('<table></table>');
for(var i=0; i < output.length; i++) {
var tr = $('<tr></tr>');
for(var key in output[i]) {
var td = $('<td></td>');
td.attr('class', key);
td.text(output[i][key]);
tr.append(td);
}
table.append(tr);
}
$('body').append(table);
Example here: http://jsfiddle.net/atrifan/4zfs57m8/3
you can even try this
var output = [{id: 1, name: 'Alex', phone: '000'}, {id: 2, name: 'Paul', phone: '010'}];
var stBldr='';
stBldr+='<table border=1>';
$.each(output,function(i,v){
stBldr+='<tr>';
stBldr+='<td>'+$(v)[0].id+'</td><td>'+$(v)[0].name+'</td><td>'+$(v)[0].phone+'</td>';
stBldr+='</tr>';
});
stBldr+='</table>';
var str=$(stBldr);
$('body').append(str);
DEMO
Related
I am using Postman to iterate through a json of about 40 pairs of items. I need to then take that array created and run an API call for each element in the array to return a set of results. Using the code here, i'm only able to pull the final element in the array. I attempted to put the postman.setNextRequest in the for loop but then I found out that no matter where it is, it always executes last.
tests["Status code is 200 (that's good!)"] = (responseCode.code === 200);
if (responseCode.code === 200) {
var jsonData = pm.response.json();
var json = [];
postman.setEnvironmentVariable("json", jsonData)
postman.setNextRequest('GetAdmins');
for (var key in jsonData ) {
if (jsonData.hasOwnProperty(key)) {
postman.setEnvironmentVariable("organizationId", jsonData[key].id)
postman.setEnvironmentVariable("orgname", jsonData[key].name)
tests[jsonData[key].name + " " + jsonData[key].id] = !!jsonData[key].name;
}
}
}
else {
postman.setNextRequest(null);
}
GetAdmins is another GET that uses {{organizationId}} in the call.
I think what i'm looking for is; what is the best way to go about running another API call on each element in the json?
Thanks in advance!
EDIT: Adding JSON output
[
{
"id": XXXXXX,
"name": "Name1"
},
{
"id": XXXXXX,
"name": "Name2"
},
{
"id": XXXXXX,
"name": "Name3"
}
]
This might work to get the data - I’ve not tried it out yet though so it might not work first time.
var jsonData = pm.response.json()
data = _.map(jsonData, item => {
organizationId: item.id
orgName: item.name
})
pm.environment.set('organizationData', JSON.stringify(data))
Then you have all of your organization data in a variable and you can use these to iterate over the Id’s in the next "Get Admins" request.
You would need to have some code in the Pre-request script of the next request to access each of the id’s to iterate over in the request. You need to parse the variable like this:
var orgID = pm.environment.get(JSON.parse("organizationData"))
Then orgID[0].organizationId would be the first one in the list.
Not a complete solution for your problem but it might help you get the data.
I was able to solve this using these two guides:
Loops and dynamic variables in Postman: part 1
Loops and dynamic variables in Postman: part 2
I also had to implement the bigint fix for java, but in Postman, which was very annoying... that can be found here:
Hacking bigint in API testing with Postman Runner Newman in CI Environment
Gist
A lot of google plus trial and error got me up and running.
Thanks anyway for all your help everyone!
This ended up being my final code:
GetOrgs
tests["Status code is 200 (that's good!)"] = (responseCode.code === 200);
eval(postman.getGlobalVariable("bigint_fix"));
var jsonData = JSON.parse(responseBody);
var id_list = [];
jsonData.forEach(function(list) {
var testTitle = "Org: " + list.name + " has id: " + JSON.stringify(list.id);
id_list.push(list.id);
tests[testTitle] = !!list.id;
});
postman.setEnvironmentVariable("organizationId",JSON.stringify(id_list.shift()));
postman.setEnvironmentVariable("id_list", JSON.stringify(id_list));
postman.setNextRequest("GetAdmins");
GetAdmins
eval(postman.getGlobalVariable("bigint_fix"));
var jsonData = JSON.parse(responseBody);
jsonData.forEach(function(admin) {
var testTitle = "Admin: " + admin.name + " has " + admin.orgAccess;
tests[testTitle] = !!admin.name;
});
var id_list = JSON.parse(environment.id_list);
if (id_list.length > 0) {
postman.setEnvironmentVariable("organizationId", JSON.stringify(id_list.shift());
postman.setEnvironmentVariable("id_list", JSON.stringify(id_list));
postman.setNextRequest("GetAdmins");
}
else {
postman.clearEnvrionmentVariable("organizationId");
postman.clearEnvironmentVariable("id_list");
}
I'm using firebase4j (a firebase library for Java, I know it is much better to go with node, I just wanted to try to do it with Java). In my database I need to persist the url of images with a bunch of the picture's information. The thing is that the picture url itself is very deep into the JSON
"users" : {
"aCategory" : {
"aUser" : {
"photos" : {
"photoUid1" : [ {
"value1" : false,
"value2" : "qwerty",
"score" : 40,
"url" : "http://someurl.com"
}
That is why I am trying to create an index for the pictures ordered by score, containing the url pointing to the location of the photo object in the firebase database. Here is where the issue begins. Firebase4j does not let you push, to a list for example, so the index ends up with this format:
{
"-UID1": {
"firebaseImgUrl": "users/aCategory/aUser/photos/photoUid1",
"score": 31
},
"-UID2": {
"firebaseImgUrl": "users/aCategory/aUser/photos/photoUid2",
"score": 30
}
}
I already added the rule ".indexOn" in order for firebase to answer with the right photos when asked for http://firebaseurl.com/users/...?orderBy="score"&limitToFirst=10, which is what I'm doing. I would like to know how should I iterate a JSON object of object as shown in the example above. I'm receiving the data from an Angular 4 client. I've tried a number of methods which haven't worked for me:
result: Photo[] = [];
for(let key in json){
console.log(key); //prints the UIDs
console.log(key.url); //url is not a property of string
//thus
result.push(new Photo(key.url, key.score)); //not working
}
The key is only a string, indicating the keys in your json. You should use it to access your object, like this:
result: Photo[] = [];
for(let key in json){
result.push(new Photo(json[key].firebaseImgUrl, json[key].score));
}
I am currently dealing with some JSON and apparently running into a bit of trouble. I have a PHP page that fetches two unrelated MySQL requests at the same time and displays both of them, one after the other. I have two JSON encodings. My issue is, I can't get my Java program to recognize the second one. First one is parsed fine.
I ran the JSON through an online validator and it is quite clear those two shouldn't follow as they are now. What is the correct way of dealing with those two ?
Please note that the comma between them (line 11) was added manually because I thought it would help. It didn't.
{
"player_update":[
{
"id":"16",
"name":"Phil_TEST",
"last_login":"2015-10-12 00:36:05",
"for_update":"00:00:00",
"newplayer":"no"
}
]
},
{
"player_list":[
{
"id":"16",
"name":"Phil_TEST",
"last_login":"2015-10-12 01:00:42"
},
{
"id":"15",
"name":"Phil8",
"last_login":"2015-10-12 00:50:49"
}
]
}
Edit : here's the code I'm using. I can parse the player_update fine, but nothing is done after I ask to find the the player_list, my Logs stop there. Test 00 AND Test 1 both don't display.
JSONObject obj = new JSONObject(stream);
JSONArray arr_player_update = obj.getJSONArray("player_update");
String newplayer = arr_player_update.getJSONObject(0).getString("newplayer");
Log.i("PhLog LobbyActivity", "Newplayer : "+newplayer);
Log.i("PhLog LobbyActivity", "Test 0");
JSONArray arr_player_list = obj.getJSONArray("player_list");
Log.i("PhLog LobbyActivity", "Test 00");
for (int i = 0; i < arr_player_list.length(); i++) {
String id = arr_player_list.getJSONObject(i).getString("id");
String name = arr_player_list.getJSONObject(i).getString("name");
String last_login = arr_player_list.getJSONObject(i).getString("last_login");
}
My PHP pages consists of : json_encode($array1);echo",";json_encode($array2);
But the comma is useless. Maybe if my JSON was valid then it would work better.
Logcat :
10-12 09:48:00.086 1052-1052/? I/PhLog LobbyActivity: Newplayer : no
10-12 09:48:00.086 1052-1052/? I/PhLog LobbyActivity: Test 0
10-12 09:48:00.086 1052-1052/? W/System.err: org.json.JSONException: No value for player_list
Problem:
The way you are encoding JSON is wrong. That was not an example of valid JSON formatted data. You can check it's validness here.
Solution :
You have two different arrays to send as response. Then combine both of them in single array first and then encode it in json format.
Example: (in your php file)
$data_to_send=array();
$data_to_send['player_update']=$player_update; // an array of player update
$data_to_send['player_list']=$player_list; // an array of player_list
json_encode($data_to_send); // to send the response
IN order to test couchbase, I am needing to create servlet that edit in 1.000 JSON documents row '"flag": false' to '"flag":true'. How i can do this?
My view, that finds documents with row '"flag": false':
function (doc, meta) {
if (meta.type == "json" && doc.flag == false) {
emit(doc.flag, null);
}
}
My servlet, that print results:
doGet(....
View view = client.getView("des1", "flag");
Query query = new Query();
query.setIncludeDocs(true);
ViewResponse result = client.query(view, query);
for(ViewRow row : result) {
resp.getWriter().println(row.getId());
}
Sorry for my bad English)
You cannot edit the fields in the JSON document directly. What you must do is to retrieve the documents you want to update (you already get them from the view), convert them to a Java object, edit the "flag" property, serialize the Java object back to JSON and replace the document with the new one.
You can use GSON to take care of the conversion between a java object and json.
I have a spring controller with a request mapping as follows
#RequestMapping("/downloadSelected")
public void downloadSelected(#RequestParam String[] ids) {
// retrieve the file and write it to the http response outputstream
}
I have an html table of objects which for every row has a checkbox with the id of the object as the value. When they submit, I have a jQuery callback to serialize all ids. I want to stick those ids into an http request parameter called, "ids" so that I can grab them easily.
I figured I could do the following
var ids = $("#downloadall").serializeArray();
Then I would need to take each of the ids and add them to a request param called ids. But is there a "standard" way to do this? Like using jQuery?
I don't know about "standard way", but this is how I would do it.
var ids = $("#downloadall").serializeArray();
will give you a dataset on the form (only the checked items presented):
[{name:"foo1", value:"bar1"}, {name:"foo2", value:"bar2"}]
To feed this to jQuery's .ajax() just:
$.ajax({
url: <your url>,
data: ids.map(function (i) {return i.name+'='+i.value;}).join('&')
});
The Array.map() is not compatible with all browsers yet so you better have this code on your page too:
if (!Array.prototype.map) {
Array.prototype.map = function(fun /*, thisp*/) {
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
This code snippet I got from mozilla developer center.
I didn't put them in a ?ids=... param, but this way they are easy to access on server side. You can always just modify the map function to fit your needs.