How to read JSON array in jQuery - javascript

I am using jQuery .load() function to load the results from server and append it in my html:
$("#content").load('Get/Information?class=Arts&min=1',
function (responseText, textStatus, XMLHttpRequest) {
console.log(responseText);
// parseJSON(responseText);
});
In my controller I tried converting my jagged array from the model into a json object and then send it to the client:
public JsonResult GetInformation(string class, int min){
var stdObj = new Student();
string[][] information = stdObj.GetInformation(class, min);
return Json(information, JsonRequestBehavior.AllowGet);
}
And after this when I check the response through console.log(responseText);
I have a jSon like string in the following format:
[
["93","Title-1","http://stackoverflow.com"],
["92"," Title-2","http://stackoverflow.com"],
["90"," Title-3","http://stackoverflow.com"],
["89"," Title-4","http://stackoverflow.com"],
["89"," Title-5","http://stackoverflow.com"],
null,null,null,null,null]
I am not sure if this a proper jSon, as from what I learn jSon is in name: value pairs, but here there are only values, considering this how can I read this string/array and print in following manner:
This just a representation(pseudo code) of how I required it to be handled:
for(int 1=0; i<response.length();i++){
$("#content").html('<h1>'+i.Id+'</h1>'+'<p>'+i.Title+'</p>'+'<span>'+i.url+'</span>')
.slideDown('slow');
// $("#content").html('<h1>39</h1>'+'<p>Title-1</p>'+'<span>http://stackoverflow.com</span>');
}

Use var dataArray = jQuery.parseJSON(response);

If your response array is
myArray =
[
["93","Title-1","http://stackoverflow.com"],
["92"," Title-2","http://stackoverflow.com"],
["90"," Title-3","http://stackoverflow.com"],
["89"," Title-4","http://stackoverflow.com"],
["89"," Title-5","http://stackoverflow.com"],
]
you can use
for(int i=0; i<myArray.length();i++)
{
$("#content").html('<h1>'+myArray[i][0]+'</h1>'+'<p>'+myArray[i][1]+'</p>'+'<span>'+myArray[i][2]+'</span>').slideDown('slow');
}
Demo: http://jsfiddle.net/KX596/1/

You need to use getJSON()
$.getJSON('Get/Information?class=Arts&min=1', function (response) {
$.each(response, function(idx, rec){
$("#content").append('<h1>'+rec.Id+'</h1>'+'<p>'rec.Title+'</p>'+'<span>'+rec.url+'</span>').slideDown('slow');
})
});

$.getJSON('Get/Information', { class: "Arts", min: 1 })
.done(function( json ) {
$.each(json , function(i, v) {
var id = v[0]; // etc
});
});
Refer to getJSON

Related

loop for fetching json data in html [duplicate]

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.
jQuery.each(data, function(index, itemData) {
// itemData.TEST1
// itemData.TEST2
// itemData.TEST3
});
you can remove the outer loop and replace this with data.data:
$.each(data.data, function(k, v) {
/// do stuff
});
You were close:
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.
You can also use the getJSON function:
$.getJSON('/your/script.php', function(data) {
$.each(data, function(index) {
alert(data[index].TEST1);
alert(data[index].TEST2);
});
});
This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.
If you use Fire Fox, just open up a console (use F12 key) and try out this:
var a = [
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];
$.each (a, function (bb) {
console.log (bb);
console.log (a[bb]);
console.log (a[bb].TEST1);
});
hope it helps
For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.
You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: data,
dataType: 'json', // ** ensure you add this line **
success: function(data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
Access the json array like you would any other array.
for(var i =0;i < itemData.length-1;i++)
{
var item = itemData[i];
alert(item.Test1 + item.Test2 + item.Test3);
}
This is what I came up with to easily view all data values:
var dataItems = "";
$.each(data, function (index, itemData) {
dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);
Try jQuery.map function, works pretty well with maps.
var mapArray = {
"lastName": "Last Name cannot be null!",
"email": "Email cannot be null!",
"firstName": "First Name cannot be null!"
};
$.map(mapArray, function(val, key) {
alert("Value is :" + val);
alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
if you don't want alert, that is u want html, then do this
...
$.each(data, function(index) {
$("#pr_result").append(data[index].dbcolumn);
});
...
NOTE: use "append" not "html" else the last result is what you will be seeing on your html view
then your html code should look like this
...
<div id="pr_result"></div>
...
You can also style (add class) the div in the jquery before it renders as html
I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},
If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.
$.get('url', function(data, statusText, xheader){
// your code within the success callback
var data = $.parseJSON(data);
$.each(data, function(i){
console.log(data[i]);
})
})
I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE
$each will work.. Another option is jQuery Ajax Callback for array result
function displayResultForLog(result) {
if (result.hasOwnProperty("d")) {
result = result.d
}
if (result !== undefined && result != null) {
if (result.hasOwnProperty('length')) {
if (result.length >= 1) {
for (i = 0; i < result.length; i++) {
var sentDate = result[i];
}
} else {
$(requiredTable).append('Length is 0');
}
} else {
$(requiredTable).append('Length is not available.');
}
} else {
$(requiredTable).append('Result is null.');
}
}

Javascript: parse json to list

I am new to javascript, sorry for silly question and possible duplicate. Please suggest me efficient way of parsing json. I would like to fetch list of strings Maktg:
{
"d":{
"results":[
{
"Maktg":"BATTERY",
"W":"1000",
"IS":"",
"IM":"",
"IW":"",
"__metadata":{
"type":"s",
"uri":"https://some_url)"
},
"IMaktg":"",
"Matnr":"0001",
"Stlan":"1"
},
{
"Maktg":"CONTROL",
//etc...
We have a JSON:
{
"d":{
"results":[
{
"Maktg":"BATTERY",
"W":"1000",
"IS":"",
"IM":"",
"IW":"",
"__metadata":{
"type":"s",
"uri":"https://some_url"
},
"IMaktg":"",
"Matnr":"0001",
"Stlan":"1"
}
]
}
}
Lest convert string JSON into more useful JavaScript object:
The JSON.parse() method parses a string as JSON, optionally
transforming the value produced by parsing.
var
jsonStr = '{"d":{"results":[{"Maktg":"BATTERY","W":"1000","IS":"","IM":"","IW":"","__metadata":{"type":"s","uri":"https://some_url"},"IMaktg":"","Matnr":"0001","Stlan":"1"}]}}';
jsonObj = JSON.parse(jsonStr),
results = jsonObj.d.results;
for (var i in results) {
console.log(results[i]['Maktg']);
/*
results[i]['W']
results[i]['IS']
results[i]['IM']
results[i]['__metadata']['type']
and etc...
*/
}
Try this:
var jsonArray = yourJSON.d.results;
var results = [];
jsonArray.forEach(function(object){
results.push(object.Maktg);
}
console.log(results);
Please try to get output with JSON.parse like this.
var getData = JSON.parse(data);
for(i=0;i<getData.d["results"].length;i++)
{
alert(getData.d["results"][i].Maktg);
alert(getData.d["results"][i].W);
//etc...
}

pass collection of objects through http post in angular js

I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}

how can pass array to java servlet

On my jsp, this is my code :
$('.save').on("click",function(){
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
var data = JSON.stringify(array);
$.post("Controller.html", data, function(response) {
/// i dont know what to put here,so i think this where i get trouble with
});
});
but still data is null when i check on servlet.
this is my servlet :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data=request.getParameter("data");
if (data== null) {
System.out.println("null");
}
RequestDispatcher view = request.getRequestDispatcher("/page.jsp");
view.forward(request, response);
}
fiddle here
First you need to send the data, you can use an ajax post method:
$.post("yourservlet", data=JSON.stringify(array), function(response) {
// handle response from your servlet.
alert(response)
});
In servlet, you retrieve the data with the command:
String data=request.getParameter("data");
Then you need to parse the json, you can use a library like JSON simple:
Object obj = JSONValue.parse(data);
JSONArray array = (JSONArray) obj;
Or you can manually parse it. Based on your code, your json string will look like this:
data = "[{'orange':['1.00','5']},{'apple':['2.00','5']}]";
You can use split() method or StringTokenizer to separate each object, but you should write your own parser method, for this you can find many tutorials on google.
Javascript is in client-side. And java servlet is for server-side.
You must use ajax to make a call from client-side to your servlet.

How get parametrs from json?

Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;

Categories

Resources