I am currently working on a script to loop through a JSON object with a fixed structure that cannot be modified.
However, I suspect the JSON is invalid because it lacks a key.
This is how my JSON looks:
{
"0": {
"name": "You",
"message": "dwd"
},
"1": {
"name": "You",
"message": "asa"
},
"2": {
"name": "You",
"message": "this is the message that the user is faced with boi"
},
...
}
I have a script in place but it doesn't seem to properly iterate over this object.
for (var key in greetings){
name = greetings[key].name
console.log(name)
msg = greetings[key].message
tag = '<ul>' + name + ' wrote: ' + message + '</ul>'
ul = ul + tag
}
Any assistance would be appreciated.
UPDATE:
Additional information: The greetings object comes from a server and is fetched using XMLHTTPRequest as shown below.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
greetings = JSON.parse(xhttp.responseText);
console.log(greetings);
}
};
The reason for reassigning variables within the loop is to format each object in the list with its own HTML tag.