I'm looking to loop through a JSON array and display the key and value.
It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop with JSON array
I also saw the post Get name of key in key/value pair in JSON using jQuery?, but it also seemed like lots of code for a simple activity.
This illustrates what I'm looking for (but it doesn't work):
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return 'johndoe#johndoe.com'
result['Phone']; // return '123'
The following should work for a JSON returned string. It will also work for an associative array of data.
for (var key in data)
alert(key + ' is ' + data[key]);
Parse the JSON string and you can loop through the keys.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var data = JSON.parse(resultJSON);
for (var key in data)
{
//console.log(key + ' : ' + data[key]);
alert(key + ' --> ' + data[key]);
}
The best and perfect solution for this issue:
I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!
Click here to see the full solution
var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);
Related
I have an ajax call that returns a Serialized JSON string with various keys and values within it, I want to loop through these values and assign each individual key and value to a different label, I already have 8 labels set up. (I am quite new to Javascript so any help or constructive feedback would be greatly appreciated)
Haven't tried much as I am quite new to JavaScript
var obj = response.ret.SearchCriteria;
var resultJSON = obj;
var result = $.parseJSON(resultJSON);
var count = Object.keys(result).length;
for (i = 1; i < count; i++) {
var c = $('#lbl' + [i]);
$.each(result, function(k, v) {
c.text(k + ' is ' + v);
});
};
I have 6 labels and the last item of the JSON array (String) is displayed in each label
I believe your issue is why only last item of JSON array is being displayed in each label.
This is because of c.text(k + ' is ' + v).
Here the existing text content is replaced with every iteration of 'each' loop
Instead, you can consider doing this, which will append existing content as well with $.each loop.
c.text(c.text() + k + ' is ' + v)
OR
Simply
c.append( k + ' is ' + v)
If I am wrong in my assumption, please describe your scenario more, so that we can help you out :)
I have a JSON but I don't know its structure (the key/value pairs that are coming in), and I need to show that info in html. I parse the string that is coming, and loop it to be able to show the info on the page in a nice manner.
<script type="text/javascript" language="JavaScript">
var jsonString = '#{CertificadoBean.certificado.resumen}';
var myObj = JSON.parse(jsonString);
for ( var x in myObj) {
if (myObj[x] instanceof Array) {
document.getElementById("json").innerHTML += "<p>" + "" + "<b>" + x + "</b>" + ": "+JSON.stringify(myObj[x]);
}
else {
document.getElementById("json").innerHTML += "<p>" + "" + "<b>" + x + "</b>" + ": " + myObj[x];
}
}
</script>
However in some cases it'll print out this:
Nivel matriculado: 10
Periodo matriculado: 2019-02
Periodos matriculados: 10
Cursos pendientes:[{"Cod.":"NIP01","Nivel":9},{"Cod.":"NI043","Nivel":10},{"Cod.":"ALE10","Nivel":10}]
I have a problem with displaying the info a nice manner when the loop finds an array in the json, and I'm not sure how to properly loop the array to display in a legible manner like the rest of the object.
How do I make Cursos pendientes show nicely like the others?
To do this, you should use JSON.stringify in javascript.
var str = JSON.stringify(obj, null, 2);
Where obj is your json. null is a replacer function ( dont use ), and 2 is a spacer ( spacing when printing )
Then you can place the stringified json on the page
document.body.innerHTML = str
See more here: Mozilla Developer Json.stringify Reference
You can wrap your JSON in a <code> or <pre> tag for a nice preview
If you really want to output it as plain html you could use some recursion (and maybe for better layout some lists). By the recursion you can ensure that all the properties (in array or just plain properties) will be shown in the same way. If you intend to do this you should care about cyclic structures and think about how to handle those. Maybe you should remove cycles entirely before outputting as html.
Here is an simple example of a recursive approach with lists:
let object2html = function(obj) {
if(! (obj instanceof Object))
return obj;
return Object.keys(obj).map(key => {
if(obj[key] instanceof Array){
return '<ul>' + obj[key].map(object2html).map(x => '<li>' + x + '</li>').join('') + '</ul>';
}
return key + ' : ' + obj[key];
}).map(toWrap => '<p>' + toWrap + '</p>').join('');
};
Look at this fiddle: https://jsfiddle.net/gqmLf79r/
Question
How can i set up a working example of of these planes.
Background
I have the first part working, so it seems that perhaps my loop is off? I can at least pull the number of planes. But having a problem displaying all the planes.
Here is my Demo on CodePen
I am looking at the documentation from https://developers.wargaming.net/reference/all/wowp/encyclopedia/planes/?application_id=demo&r_realm=eu
but they don't have a fully functioning example. I want to show the name of the plane, country, and show a large image. I can style it later but need a working example to help me understand and get started.
Code
API
I am pulling data from https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo
JSON output
HTML
<p>There are a total of <span id="planeQuantity"></span> planes in the database.</p>
<ul id="planes"></ul>
jQuery from
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
Javascript
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
var name = data.id.name_i8n;
var nation = data.id.nation;
var lrgImg = data.id.images.large;
$(data).each(function(){
console.log($(this).id);
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
})
I adjusted your code a bit. Some comments:
your data.data is a Object. so, you can use for (key in object) for each key iteration (you can use jQuery's each too, but this is a pure JS approach);
name_i8n is, actually, name_i18n;
put all your var = name, var = nation and var = lrgImg into inside the loop.
Final code:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
for (key in data.data) {
var item = data.data[key];
var name = item.name_i18n;
var nation = item.nation;
var lrgImg = item.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
}
})
Working pen: http://codepen.io/mrlew/pen/vgaexb
Edited with some explanation
You received a data Object that have a data key whose value is a huge Object with this structure (more or less):
{
"7290": { /* ... */ },
"7291": {
"name_i18n": "North American FJ-1 Fury",
"nation":"usa",
"images":{
"large":"http://worldofwarplanes....png",
/* ... */
},
/* ... */
},
"7292": { /* ... */ }
}
So, to iterate over all keys of data.data keys we can use for (key in data.data) { }.
In each iteration, key variable will be assigned to a object key: 7290, 7291, 7292. So, to access it's value, we use data.data[key] (will be data.data["7291"], for instance), and assigned the variable item with the value.
Using brackets like this is one way in JavaScript to retrieve a value from an Object. Another way is to use dot notation (but you can't use dot notation with a key that's a number).
This is valid:
data["data"]["7291"]
This is invalid:
data.data.7291
You should set the values of name, nation and lrgImg inside each. So the elements you append won't all have the same thing. And you should loop through the data object that is inside your data object (data.data). Like this:
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/?application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(key, value){
var name = value.name_i18n; // get the name of this data entry
var nation = value.nation; // get the nation of this data entry
var lrgImg = value.images.large; // ...
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
var queryURL = "https://api.worldofwarplanes.eu/wowp/encyclopedia/planes/? application_id=demo";
$.getJSON(queryURL, function (data) {
var quantity = data.meta.count;
$('#planeQuantity').append( quantity );
$.each(data.data, function(i, e) {
var name = e.name_i18n;
var nation = e.nation;
var lrgImg = e.images.large;
$('#planes').append('<li>' + name + 'is from ' + nation + '<img src="' + lrgImg + '">' + '</li>');
});
});
You need to iterate through data.data object. Since you aren't working with dom nodes use $.each() instead of $.fn.each()
$.each(data.data, function(key, obj){
console.log(key) // "4101"
console.log(obj.name) // "type=91"
})
The json output is some thing like:
{"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}
I need to do an append with each of the received values. The numbers next to them are how many times they exist.
I know it will probably be something with "for each" value, but, since the values and keys of the json response are variable, it's difficult for me how to figure out the way to do it.
I will like that the append order depends on how big the number is. If it's bigger print it on the top, and so on...
for example:
<div id="values">
<p>The value "more" is repeated 5 time(s).</p>
<p>The value "apple" is repeated 3 time(s).</p>
<p>The value "another" is repeated 1 time(s).</p>
...
</div>
Remember! The response can change, the response won't be always apple, another, more, volvo, audi and ford... It can CHANGE!
EDIT:
I can do something with this, but, how do I order them with higher or lower values?
for (var key in interests) {
if (interests.hasOwnProperty(key)) {
console.log(key + " -> " + interests[key]);
}
}
EDIT:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1}; // initial data
var interestsValue = []; // data with values
for (var key in data){ interestsValue.push({ name: key, value: data[key] }); } // send data with values
interestsValue.sort(function(a, b){ return b.value - a.value; }); // sort values
console.log(interestsValue); // values ordered from bigger to smaller
First - convert the object to a valid array:
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
var arr = [];
for (var key in data)
{
arr.push({ name: key, value: data[key] });
}
Then.... use that array with jQuery, angular, etc... to populate your elements
Enjoy :)
Like this.Loop through your objcet using jquery's $.each method Then append the html into your div with append method.
var obj= {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
text = "";
$.each(obj,function(index,element){
text +=" <p>The value " +index+ " is repeated "+ element + " time(s).</p>";
});
$("#values").append(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="values">
</div>
JS fiddle https://jsfiddle.net/uobedcf0/
See UPDATED Fiddle:
https://jsfiddle.net/u1kn6d6L/1/
As mention above first convert object into the array.
var data = {"apple":3,"another":1,"more":5,"volvo":1,"audi":1,"ford":1};
function sortByValue (data){
var dataArray=[];
for(var key in data){
dataArray.push({name:key ,value :data[key]});
}
dataArray.sort(function(a,b){return b.value- a.value}); //sort it in descreasing order
return dataArray;
}
var text="";
var objArray = sortByValue(data);
$.each(objArray,function(index,object){
text +=" <p>The value " +object.name+ " is repeated "+ object.value + " time(s).</p>";
});
$("#values").append(text)
I have a JSON string that looks like this:
{"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
In Javascript, I'm trying to output the strings by category (cat1-3), this is my code so far.
$.post(loadUrl, function(data){
$("#result").html("<p>Cat1: " + data.cat1 + "</p><p>Cat2: " + data.cat2 + "</p>");
});
I would normally not use JSON (Usually JSTL) but since I want to learn AJAX, I want to try output the cat1-3 values by the key, which I keep getting "undefined".
I was using this as a guide to get the values: http://www.skill-guru.com/blog/2010/01/27/json-javascript-tutorial/
Try below script
va response = {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
var obj = jQuery.parseJSON(response);
alert(obj.cat1);
it will return m1
var a = JSON.parse("{\"cat1\":\"m1\",\"cat2\":[\"d1\",\"d2\",\"d3\"],\"cat3\":[\"m1\",\"m2\",\"m3\",\"m4\"]}");
for(key in a)
{
alert(key);
alert(a[key]);
}