如果事先不知道值名称,如何访问嵌套JSON中的值。
即。在下面的JSON中,我需要访问糖果选项的名称,以将它们添加到SQLite表中。但是糖果类型以及它们的每个糖果选项名称都不是事先知道的。
JSON的样本可能如下所示,其中可以有任意数量的糖果选项,每个选项都有自己的选项数。
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"
}]
}]
要将每个糖果选项插入数据库,我尝试以下操作,但没有运气。
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
});
}
});
}
答案 0 :(得分:2)
查看您提供的内容,您可以使用以下代码遍历所有这些对象:
data.forEach(function(dataset) // A variable to hold the confectionary JSON
{
Object.keys(dataset).forEach(function(key)
{
// Inner loop for nested JSON objects
if(Array.isArray(dataset[key])) {
dataset[key].forEach(function(item)
{
console.log(item)
// Use v and k to insert into database
});
} else {
console.log(dataset[key])
}
})
});