user3645783
user3645783

Reputation: 25

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!

Upvotes: 1

Views: 5785

Answers (1)

Drazen Bjelovuk
Drazen Bjelovuk

Reputation: 5472

You're iterating over d as if it's an array rather than an object. Something like this is probably 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);
}

Upvotes: 1

Related Questions