I have the following javascript array:
[{
"id": "115",
"poster": "809",
"post": "alfa"
}, {
"id": "127",
"poster": "808",
"post": "beta"
}]
What do I need to do in order to extract the values into usable variables?
Try this,
var arr = [{"id":"115","poster":"809","post":"alfa"},{"id":"127","poster":"808","post":"beta"}];
for (i = 0; i < arr.length; i++)<br/>
document.write("id: " + arr[i].id + " poster: " + arr[i].poster + " post: " + arr[i].post + "<br/>");
What you have is an array with two elements
data = [a,b]
where both elements a and b are objects each having three fields (id,poster,post).
Recall that to access an element in the array at position i you simply write data[i] (this will access the ith element in your array i.e. one of the objects).
In order to access a field of the object a you simply use a.fieldName. For example a.id will access id field of object a. If you combine them both you can get data[i].fieldName to access field of specific object (for example data[0].id will return "115").
As a side note, array structures are iterable:
for(var i = 0;i<data.length;i++){
id = data[i].id;
post = data[i].post;
poster = data[i].poster;
document.write(id+" "+post+" "+poster+"<br/>");
}
UPDATE: Example on jsFiddle
Related
In my react app, I have two JSON objects that contain user quiz results. My goal is to generate a percentage value of how many answers each quiz in the roomSurveys has in common with the userSurvey answers using some sort of loop within a loop.
const [userSurvey, setUserSurvey] = useState({ "Q1":"A",
"Q2":"B, C, A",
"Q3":"C" });
const [roomSurveys, setRoomSurveys] = useState({
"user2":{ "Q1":"A",
"Q2":"B, C, C",
"Q3":"B" },
"user3":{ "Q1":"C",
"Q2":"B",
"Q3":"B" },
});
The function that calculates the answers in common would then update a state like this:
const [roomMatches, setRoomMatches] = useState({
"user2":{ "percentMatch":"1.0"},
"user3":{ "percentMatch": ".30"}
})
here is what I've got so far:
//loop through each user survey in the roomSurvey object
for (var key of Object.keys(roomSurveys)) {
var countSame;
var countTotal;
//loop through each user survey within the roomSurvey object
for (var key of Object.keys(roomSurveys[key])) {
//if answer matches userSurvey answer for the same key,
//add to count same and count total else, add to count total
if(roomSurveys[key] == userSurvey[key]){
countSame++;
countTotal++;
}else{
countTotal++;
}
console.log(key + " -> " + roomSurveys[key])
console.log(key + " -> " + userSurvey[key])
}
var percentMatched = countSame/countTotal;
setRoomMatches([...roomMatches, {key:{['percentMatch']: percentMatched}}]);
}
here are the errors I am getting:
In the second for loop, the roomSurveys[key] value is always undefined
roomMatches is not iterable (when trying to add new match percent to roomMatches state)
You have ovewritten your key variable int the second for loop. You need to name them key1 and key2 (or something more verbose)
You're using the same name for key variables, rename them and use them as desired.
... V
for (var survey of Object.keys(roomSurveys)) {
var countSame;
var countTotal;
v
for (var room of Object.keys(roomSurveys[survey])) {
...
I came across an exercise in freeCodeCamp to convert json data to html. Here, I was asked to copy paste a jquery which I didn't understand.
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'cat'>";
keys.forEach(function(key) {
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
html += "</div><br>";
});
This is my json
[
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on it's head. ",
"codeNames":[
"Juggernaut",
"Mrs. Wallace",
"Buttercup"
]
},
{
"id":1,
"imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
"altText":"A white cat with blue eys, looking very grumpy. ",
"codeNames":[
"Oscar",
"Scrooge",
"Tyrion"
]
},
{
"id":2,
"imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
"altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
"codeNames":[
"The Doctor",
"Loki",
"Joker"
]
}
]
Can anyone help me to break down this code and tell what each line in the code does? For example I don't know what Object.keys does. Is Object an inbuilt instance?
The Object.keys() method returns an array of a given object's own enumerable properties.
var keys = Object.keys(val);
Here 'keys' is the array form of your json.
According to the JSON you provided the array has 3 objects.
You can also write
Object.keys(val).forEach(function(key){
//something
});
instead of
var keys = Object.keys(val);
keys.forEach(function(key) {
//something
});
Inside the loop the key returns the the key of your object i.e.
id, imageLink etc
and
val[key] return corresponding values e.g.
0, "https://s3.amazonaws.com/freecodecamp/funny-cat.jpg" to be more specific.
From MDN
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.
The purpose of the code is to generate html by using key and corresponding value.
var json = [
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on it's head. ",
"codeNames":[
"Juggernaut",
"Mrs. Wallace",
"Buttercup"
]
},
{
"id":1,
"imageLink":"https://s3.amazonaws.com/freecodecamp/grumpy-cat.jpg",
"altText":"A white cat with blue eys, looking very grumpy. ",
"codeNames":[
"Oscar",
"Scrooge",
"Tyrion"
]
},
{
"id":2,
"imageLink":"https://s3.amazonaws.com/freecodecamp/mischievous-cat.jpg",
"altText":"A ginger cat with one eye closed and mouth in a grin-like expression. Looking very mischievous. ",
"codeNames":[
"The Doctor",
"Loki",
"Joker"
]
}
]
var html = "";
//iterating through all the item one by one.
json.forEach(function(val) {
//getting all the keys in val (current array item)
var keys = Object.keys(val);
//assigning HTML string to the variable html
html += "<div class = 'cat'>";
//iterating through all the keys presented in val (current array item)
keys.forEach(function(key) {
//appending more HTML string with key and value aginst that key;
html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
});
//final HTML sting is appending to close the DIV element.
html += "</div><br>";
});
document.body.innerHTML = html;
Following is the JSON array, I want to get number of parent objects and then run for loop on them to get each object value.
It should give total count 2 as I have two parent objects - canvas0 and canvas1.
{"canvas0":
"{"objects":
[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage1","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"
,"canvas1":"{"objects":[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage2","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"}
As everyone said, your JSON is invalid. The same valid JSON in minimal would look like the following.
var json = {
"canvas0": {
"objects": [
{
"type": "textbox",
"originX": "left"
}
],
"background": "#000"
},
"canvas1": {
"objects": [
{
"type": "select",
"originX": "right"
}
]
}
};
To be able to iterate thru, you don't need the count of top level keys. And moreover, a JSON object doesn't have the length property. All you need to do is, use for...in loops and display the key/values accordingly. Here is an example of how you can do it. Bear in mind that this only works with your specific case as the loop needs changing as and when the JSON levels change.
alert ( "Length of top level keys: " + Object.keys(json).length );
for (var key in json) {
var canvas = json[key];
for (var key2 in canvas) {
if (canvas[key2] instanceof Array) {
var object = canvas[key2][0];
for (var key3 in object) {
alert (key3 + ": " + object[key3]);
}
} else {
alert (key2 + ": " + canvas[key2]);
}
}
}
Here is a working demo with the complete code.
I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have
//access DB, returns a list of User objects, ordered
ArrayList users = MySQLDatabaseManager.selectUsers();
//construct response
JSONObject jsonResponse = new JSONObject();
int key = 0;
for(User user:users){
log("Retrieve User " + user.toString());
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", user.getName());
jsonObj.put("time", user.getTime());
jsonResponse.put(key, jsonObj);
key++;
}
//write out
out.print(jsonResponse);
From the log I can see that the database returns User objects in the correct order.
At the front-end, I have
success: function(jsonObj){
var json = JSON.parse(jsonObj);
var id = 0;
$.each(json,function(i,item) {
var time = item.time;
var name = item.name;
id++;
$("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time +
'</td><td>' + name +
'</td></tr>');
});
},
But the order is changed.
I only noticed this when the returned list has large size (over 130 users).
I have tried to debug using Firebug, the "response tab" in Firebug shows the order of the list is different with the log in the servlet.
Did i do anything wrong?
EDIT: Example
{"0":{"time":"2011-07-18 18:14:28","email":"xxx#gmail.com","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":
,...,
"143":{"time":"2011-08-09 09:57:27","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}
,...,
"134":{"time":"2011-08-05 06:02:57","email":"xxx#gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):
jsonObj =
{ items:
[ { name: "Stack", time: "..." },
{ name: "Overflow", time: "..." },
{ name: "Rocks", time: "..." },
... ] };
This structure will ensure that your objects are inserted in the proper sequence.
Based on the JSON you have above, you could place the objects into an array and then sort the array.
var myArray = [];
var resultArray;
for (var j in jsonObj) {
myArray.push(j);
}
myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });
for (var i = 0; i < myArray.length; i++) {
resultArray.push(jsonObj[myArray[i]]);
}
//resultArray is now the elements in your jsonObj, properly sorted;
But maybe that's more complicated than you are looking for..
As mentioned by ghayes , json objects are unordered.
There are multiple solutions to this problem.
You can use array and the sort it to get the ordered list.
You can use gson library to get the desired order of elements.
I would prefer the second option as it is easy to use.
As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files
https://github.com/abinash1/Sorted-Json-Object
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>");