jQuery.each - How to iterate over JSON objects element? - javascript

i am very new to play with JSON. I need to iterate over JSON response coming from AJAX, actually, i am fetching checkboxe values from db table in the form on 2,3,7,9,3. Now i am stuck with iteration on each number.
If you run following code in FF console area you will notice it is looping against each numeric NOT THE VALUE.
Please guide me.
var srv = {"services":"26,29"};
jQuery.each( srv.services, function(i, v) {
console.log( v );
});
Any help would be appreciated.
THanks :)

srv.services is a string of comma separated values, so $.each() won't work correctly. You can split() it into an array, though:
var srv = {"services":"26,29"};
jQuery.each(srv.services.split(","), function(i, v) {
console.log( v );
});
Working demo: http://jsfiddle.net/AndyE/veP4p/
You could also have your JSON service return an array instead of a string, e.g. {"services":[26, 29]}. This would be done for you automatically at the server if you're using proper JSON-compliant methods to encode and if the data is an array.

it is not valid json array, your json data should be something like this:
var srv = {"services": ["26", "29"]};
..or of-cause you could split your string data using js split function:
jQuery.each(srv.services.split(","), function(i, v) {
console.log( v );
});

Not sure this is an answer to your problem but given the declaration from above, try splitting on , before iterating:
var srv = {"services":"26,29"};
jQuery.each( srv.services.split(','), function(i, v) {
console.log( v );
});
(Demo)

You have to create an array first
var srv = {"services":"26,29".split(",")};
jQuery.each( srv.services, function(i, v) {
console.log( v );
});

Related

How to extract json, multiple value using jquery

Hello I have a json data like this
KLOBS {"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":["0.00247320692497939","0.000008129750823137272"]}
KL15 {"SL_VEF_APPLIED_VS_BOL_R1_KL15":["0.01890831252229754","0.9008162336184189"]}
I'm already try extract json
$.get('url_request.php?' + $(this).serialize(), function(data) {
var obj = data;
$.each(obj, function(key, value) {
console.log(key);
console.log(value);
});
});
$.each(obj, function(key, value) {
console.log(key);
console.log(value);
});
And I get result
KLOBS
{"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":["0.00247320692497939","0.000008129750823137272"]}
KL15
{"SL_VEF_APPLIED_VS_BOL_R1_KL15":["0.01890831252229754","0.9008162336184189"]}
I want to get result like this:-
KLOBS
0.00247320692497939
0.000008129750823137272
KL15
0.01890831252229754
0.9008162336184189
How to call json like this ??
I don't know call multiple value data in Json.
Please help me.
Try this
var arr = {
KLOBS: {
SL_VEF_APPLIED_VS_BOL_R1_KLOBS: [
"0.00247320692497939",
"0.000008129750823137272"
]
},
KL15: {
SL_VEF_APPLIED_VS_BOL_R1_KL15: ["0.01890831252229754", "0.9008162336184189"]
}
};
Object.keys(arr).forEach(function(key, value) {
console.log(key);
Object.keys(arr[key]).forEach(function(val) {
arr[key][val].forEach(function(data) {
console.log(data);
});
});
});
In general you could do the following:
var KLOBS = {"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":
["0.00247320692497939","0.000008129750823137272"]}
values = Object.keys(KLOBS).map(x=>{
return KLOBS[x];
})
values.forEach(x=>x.forEach(y=>console.log(y)))
jsfiddle
Object.keys gives you an array of the keys in an object.
Since I do not know the structure in advance, I assume it better thinking of more than one key.
With the function map, a function is applied to each member of the array returned by Object.keys. This is used to extract the values.
The resulting structure is an array of arrays.
Therefore a double forEach is needed to display every entry of the structure.

How to get the second data of this JSON in jQuery?

How can I get the second data of this JSON - I am beta. in jQuery?
{"alpha":["I am alpha"],"beta":["I am beta."]}
You can go through array and search for keys what you want... but dont forget to encode json string
$data= json.encode($input)
foreach($data as $key => $val)
{
if($key=='beta')
do something
else
do something else
}
I hope it help you.
Assuming that your json is in a string variable as:
var data = '{"alpha":["I am alpha"],"beta":["I am beta."]}';
You can parse the string as a json object and then access the content like this:
json = JSON.parse(data);
//or if you strictly need to use jQuery
json = $.parseJSON(data);
alert(json.alpha[0]);
alert(json.beta[0]);
If you don't know which is the json content you can iterate through json object like this:
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(key + " -> " + json[key]);
}
}
Finally I come up with this
Step 1: Json parsed,
Step 2 : Declared in another string
Step 3 : And then looped inside each entry
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br/>';
});
$('#stage').html(error_string);
}
And then i got the values that is inside, Now i can able to get the values inside the object even for n numbers.

Each jquery get values

Here I have this code jquery:
JSON.stringify($("#vrsta_rada").select2("data"));
and I get this JSON file:
"[{"id":2,"text":"setva/zasad"},{"id":6,"text":"orezivanje"},{"id":8,"text":"skladistenje"}]"
How I can use .each function to get this string: data[0].text, data[1].text ...
so to get string from JSON above: setva/zasad, orezivanje, skladistenje
?
I'm not sure why you are stringifying the data if you want to manipulate it. So this will work:
var data = $("#vrsta_rada").select2("data");
$.each(data, function(key, value) {
var text = data[key].text
//or
var text = value.text
});
Is this what you are looking for? That will iterate through the list. I prefer to use data[key] because you can then manipulate the data and it will change the original whereas value only makes a copy.
Try
$.each(data, function(index, value) {
alert(value.text)
});

Printing JSON Dictionary in JavaScript

I am getting the data from an API using JavaScript.
The statement console.log(json[0]) gives the result:
{"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"}
Now I am trying to print the individual elements of this dictionary. How do I do this ? My code is below:
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
});
}
EDIT:
The value of data as returned by the API is
["{\"id\":\"1\",\"username\":\"ghost\",\"points\":\"5\",\"kills\":\"18\",\"xp\":\"10\",\"diamonds\":\"0\",\"level\":\"1\",\"missionscomplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionscomplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionscomplete\":\"4\"}"]
The value in json after the operation var json = $.parseJSON(data); is
["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionscomplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionscomplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionscomplete":"4"}"]
You can just use stringify method of JSON-
console.log(JSON.stringify(json[0]));
Update
Your JSON data is a mess. It's not in the format you want. It should be an array of objects, but instead it is an array of strings, where each of those strings is the JSON representation of one of your user objects.
You could decode this in your JavaScript code, but you shouldn't have to. The JSON API should be fixed to generate a reasonable JSON object.
I don't know what language your server code is in, but it must be doing something like this pseudocode:
array = []
for each userObject in leaderBoard:
userJson = toJSON( userObject )
array.push( userJson )
jsonOutput = toJSON( array )
Instead, the code should look more like this:
array = []
for each userObject in leaderBoard:
array.push( userObject )
jsonOutput = toJSON( array )
In other words, the way to generate the JSON you want in most languages is to create an object or array with the structure you need, and then call the language's toJSON function (or whatever function you use) on that object or array. Let it generate all of the JSON in one fell swoop. Don't generate JSON for each individual element of your array and then generate JSON again for the entire array as a whole. That gives you an array of strings where you want an array of objects.
Original answer
What you're asking for is not what you really want to do.
Your JSON response returns an array of user objects, correct? That's why json[0] is a single object.
You probably want to loop over that array, but you don't loop over the individual objects in the array. You simply reference their properties by name.
Also, instead of using $.get() and $.parseJSON(), you can use $.getJSON() which parses it for you.
And one other tip: don't put the hostname and port in your URL. Use a relative URL instead, and then you can use the same URL in both development and production.
So for test purposes, let's say you want to log the id, username, and points for each user in your leaderboard JSON array. You could do it like this:
function loadLeaderboard() {
var url = '/l4/public/api/v1/getLeaderboard';
$.getJSON( url, function( leaders ) {
// leaders is an array of user objects, so loop over it
$.each( leaders, function( i, user ) {
// get the properties directly for the current user
console.log( user.id, user.username, user.points );
});
});
}
json[0] is an object, so you want to loop over the keys:
var o = json[0];
for (var key in o) {
if (o.hasOwnProperty(key)) {
console.log(key, o[key]);
}
}
Working fiddle: http://jsfiddle.net/UTyDa/
jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/
eg
$.each(json[0], function(key, data) {
console.log(key + ' -> ' + data);
});
EDIT:
What's the result of the following?
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
for(var i = 0; i < json.length; i++) {
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
}
});
}
EDIT 2: 'data' returned as array.
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard", function(data){
for(var i = 0; i < data.length; i++) {
var json = $.parseJSON(data[i]);
console.log('Data for index: ' + i);
$.each(json, function(key, val) {
console.log(key + ' -> ' + val);
});
}
});
}

Display elements in my 2d Array in Javascript

I have a post function that returns a 2d array. How would I go about displaying each of the elements in it? My code looks something like this :
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(result) {
//$("#CustomerList tbody").append($(result));
var myarray = new Array()
myarray = result;
alert(myarray);
});
what the alert returns is "System.String[][]". How can i go about appending each of the values from my array to my div tag called #divComparativeQuestions.
For example:
var data = new Array();
for(var i=0;i<myarray.length;i++){
data.push(myarray[i].join(', '));
}
$('#divComparativeQuestions').html(data.join('<br/>'));
(hope this works, not tested :), but you get the idea )
I'm guessing you want something like:
// given an array [[1,2],[3,4]] with a desired result of <div>1234</div>
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(data) {
if(data) {
var div = $('#divComparativeQuestions');
$.each(data, function(index, element) {
div.append(element); // will be inner array of [1,2] or [3,4]
});
}
});
All pretty basic stuff, in this case I'm taking advantage of the fact js typically flattens array as strings without commas to get the desired out put, but if you want to delimit them items somehow or wrap them in tags or whatever, it's easy enough to work out by taking a few seconds to browse http://docs.jquery.com

Categories