Extract from Ajax response - javascript

I have an ajax call that returns JSON data (Data Attached).
After converting the data into String, this is how it looks like:
{
"shipments":[
{
"companyName":"TriStar Inc.",
"shipmentDate":null,
"transMode":"NDAY",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"DAISY N.",
"customerZip":"90544"
},
"orderStatus":true
},
{
"companyName":"Carbo Box",
"shipmentDate":null,
"transMode":"COUR",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"TOM K",
"customerZip":"07410"
},
"orderStatus":true
}
]
}
Now when I print the JSON response in Firefox, it looks like:
[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]
My question is, how do I extract companyName and customerName field out of this response. The following isnt working:
load: function(response){
for(var i in response){
console.log(response.shipments[i].companyName);
}

if you get a string that is json, you need to parse it first.
var obj = JSON.parse(jsonString);
now you have a proper object literal, and you can access it normally
var shipments = obj.shipments;
shipments is now a javascript array...
for(var i = 0; i < shipments.length; i++){
console.log(shipments[i].companyName);
}
note you should not use the for(var i in x) construct on arrays.

response.shipments[i].companyName

Related

Getting null in when trying to get array in servlet

I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");

Looping through JSON data in javascript not working

I have some JSON data being returned from an AJAX call. I then need to parse this data in javascript.
The data looks like so:
[
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
]
Why is it when i run this code on the data that i get multiple undefined's?
(var json being the variable holding my json data)
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
However if i assign the json directly to the variable like so:
var json = [
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
];
Then it works fine!
Any ideas guys? Thanks
Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.
Example:
var string_json = '[{"a":1},{"b":2}]'; // may be your API response is like this
var real_json = JSON.parse(string_json); // real_json contains actual objects
console.log(real_json[0].a, real_json[1].b); // logs 1 2
It is not a JSON that, you are using.
It's an object array.
When you get JSON, parse that JSON using method JSON.parse.
Assign this JSON to a variable and then use iteration over it...
Ex:
var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
var parsedJson = JSON.parse(json);
for(var i = 0; i < parsedJson.length; i++) {
var obj = parsedJson[i];
console.log(obj.id);
}

loop over array and add separate objects to new array - only one item in new array

I am making a call to a backend API which returns a JSON response. I have read a number of answers on here including this but they dont seem to cover my issue.
The JSON response from the API looks like this:
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
}
]
My Angular JS code looks like this:
controller.testDetailHolder = [];
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder.name = data[i].name;
controller.testDetailHolder.id = data[i].id;
}
});
When I console.log controller.testDetailHolder it only shows the second value from the GET request (i.e. the array just holds one value) however, I want the controller.testDetailHolder to look like this:
controller.testDetailHolder = [
{
id: "1",
name: "test1",
},
{
id: "2",
name: "test2",
}
]
Any assistance with this would be greatly appreciated.
Thanks.
controller.testDetailHolder = [];
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder.push({
name : data[i].hours,
id : data[i].id
});
}
});
Your loop is constantly overwriting controller.testDetailHolder, so you need to use array syntax:
Test.getAllTests.query({}, function(data){
for(var i=0; i<data.length;i++){
controller.testDetailHolder[i].name = data[i].hours;
^^^
controller.testDetailHolder[i].id = data[i].id;
}
});
You can assign the data like:
Test.getAllTests.query({}, function(data){
controller.testDetailHolder = data;
});
Or use push to add it to the existing array:
Test.getAllTests.query({}, function(data){
Array.prototype.push.apply(controller.testDetailHolder, data);
});
controller.testDetailHolder is the array itself, not an element within the array. You want to add the values as elements, which is accessed by controller.testDetailHolder[i], where i is the index of the element. Modify your code to be:
controller.testDetailHolder[i].name = data[i].hours;
controller.testDetailHolder[i].id = data[i].id;
The problem is that you are completely overwriting the complete testDetailHolder array, because you do not specify an index when setting the values.
controller.testDetailHolder.name should be controller.testDetailHolder[i].name
Another issue is that you are using data[i].hours when hours is not defined on the JSON.
Lastly since you want to copy the whole object you could just do a single assignment
Test.getAllTests.query({}, function(data){
controller.testDetailHolder = data;
});

How do i iterate through JSON array in javascript?

I have a json data coming from rest in following format:
{
"status_code": 200,
"data": {
"units": -1,
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day",
"countries": [{"country": "IN", "clicks": 12}]},
"status_txt": "OK"
}
I want to access the countries part and need to generate data in format like
{"IN":12, ......}
I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?
I tried this:
$.each(response.countries, function(key, value) {
console.log(value.country + ": " + value.clicks);});
but it is showing me type error e is undefined...
Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:
var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
var tmp = data.data.countries[i];
obj[tmp.country] = tmp.clicks
}
console.log(obj); // { IN: 12, UK: 123 }
DEMO
Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):
var obj = {};
$.each(response.data.countries, function(key, value) {
obj[value.country] = value.clicks;
});
If you want a string instead of an object, just JSON.stringify the obj:
var json = JSON.stringify(obj);
DEMO

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories