user3645783 user3645783 - 6 months ago 29
Javascript Question

Inserting JSON data into Sqlite/webSQL database

I am pulling data from my remote database and get this JSON data:

{"list1":{"id":1, "item":"testobj1"},"list2":{"id":2, "item":"testobj2"},"list3":{"id":3,
"item":"testobj3"},"list4":{"id":4, "item":"testobj4"},"list5":{"id":5, "item":"testobj5"}}


I can now loop through the objects in the data and display a list of objects on my screen. It works fine:

var d = JSON.parse(hr.responseText);
databox.innerHTML = "";
for (var o in d) {
if (d[o].item) {
databox.innerHTML += '<p>' + d[o].item + '</p>' + '<hr>';

}
}


Now however, I would like to insert this data into my Sqlite database. I am not quite sure how I can tell the loop that 'd[o].id' and 'd[o].item' are the items I would like insert into my db.

db.transaction(function(tx) {
var sql = "INSERT OR REPLACE INTO testTable (id, item) " + "VALUES
(?, ?)";
log('Inserting or Updating in local database:');
var d = JSON.parse(hr.responseText);
var id = d[o].id;
var item = d[o].item;
for (var i = 0; i < d.length; i++) {
log(d[o].id + ' ' + d[o].item);
var params = [d[o].id, d[o].item];
tx.executeSql(sql, params);
}
log('Synchronization complete (' + d + ' items synchronized)');
}, this.txErrorHandler, function(tx) {
callback();
});


I hope somebody can take a look at this loop and tell me where did I go wrong. Many thanks in advance!

Answer

You're iterating over d as if it's an array when it seems to be an object. I would think something like this is what you're looking for:

var d = JSON.parse(hr.responseText);
for (var o in d) {
    var params = [d[o].id, d[o].item];
    tx.executeSql(sql, params);
}