I am following this tutorial to learn how to insert Text from a JSON into an Website. I rebuilt the example on the website succesfully - however I struggle to use my own JSON, which has a slightly different structure.
The JSON from the tutorial looks like this:
[
{
"id": "1",
"firstName": "John",
"lastName": "Doe"
},
{
"id": "2",
"firstName": "Mary",
"lastName": "Peterson"
},
...
]
The array is loaded into an object called data and I can access each of its values using an index and the key of the value i.e. data[0].firstName would result in "John" (as described in the short tutorial).
Now, the JSON I actually want to use has the following structure:
{
"Category1": [
{
"name": "Lorem",
"description": "A description",
"product": "a product",
...
}
],
"Category2": [
{
"name": "Lorem1",
"description": "Another description",
"product": "another product",
...
},
{
"name": "Lorem2",
"description": "A third description",
"product": "a third product"
...
},
{
"name": "Lorem3",
"description": "And one last description",
"product": "last product",
....
}
],
"Category3": [
{
...
},
],
...
}
How can I access all of these values? I tried to treat the data object as a multidimensional array (i.e. data[0][1] without success.
I am using the following function to insert into the HTML:
function appendData(data) {
var mainContainer = document.getElementById("myData");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[i].firstName;
mainContainer.appendChild(div);
}
}
Also - as a follow-up question: Is there a way to iterate through the Categories at all?