How do I access values in a nested JSON if the value names are not know to me in advance.
I.e. in the JSON below I need to access the names of the confectionery options to add them to a SQLite table. But the types of confectionery as well as their each confectionery option names aren't know to me in advance.
A sample of the JSON may look like this, where there can be any number of confectionery options, each with its own number of options.
JSON
[{
"sweet": "sweets",
"sweets":
[{
"idsweets": "1",
"sweetsdesc": "Choocolate Chip"
}, {
"idsweets": "2",
"sweetsdesc": "Mint"
}],
"drink": "drinks",
"drinks":
[{
"iddrinks": "1",
"drinksdesc": "Coke"
}, {
"iddrinks": "2",
"drinksdesc": "Pepsi"
}, {
"iddrinks": "3",
"drinksdesc": "Fanta"
}, {
"iddrinks": "4",
"drinksdesc": "Dr. Pepper"
}, {
"iddrinks": "5",
"drinksdesc": "Powerade"
}],
"crisp": "crisps",
"crisps":
[{
"idcrisps": "1",
"crispsdesc": "Salt"
}, {
"idcrisps": "2",
"crispsdesc": "Vinegar"
}, {
"idcrisps": "3",
"crispsdesc": "Cheese and Onion"
}, {
"idcrisps": "4",
"crispsdesc": "Pepper"
}, {
"idcrisps": "5",
"crispsdesc": "Chilli"
}, {
"idcrisps": "6",
"crispsdesc": "Other"
}]
}]
To insert each confectionery option into the Database I try the following, but with no luck.
function goInsertValueOptionsList()
{
db.transaction(insertValueOptionsList, errorCB, successCB);
}
function insertValueOptionsList(tx)
{
angular.forEach($scope.optionValuesAPIData, function (value, key) // A variable to hold the confectionary JSON
{
alert("Value Options - Value: " + value); // Prints the JSON [object Object]
for (var description in value)
{
// Get the Column name
alert("Value Options - Description (Column name): " + description);
// Get the Column value
alert("Value Options - Description (Column Value): " + value[description]);
// Inner loop for nested JSON objects
angular.forEach(value, function (v, k)
{
// Get the Column name - try to access e.g. idcrisps
alert("V Options - Description (Column name): " + v); // Not working
// Get the Column value
alert("V Options - Description (Column Value): " + k); // Not working
// Use v and k to insert into database
});
}
});
}