Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store JSON objects in indexedDB?

my return json file looks like this:

var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];

without JSON.stringify data looks like this:

[object Object],[object Object],[object Object]

but with it the result.length is not 5 but the total number of characters of the string and that way I cant do the loop

var result = JSON.stringify(data);
for(i=0; i<result.length; i++){
var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE);
var put = transaction.objectStore(STORE).put(result);
};   
like image 782
Ruben Teixeira Avatar asked Sep 26 '12 17:09

Ruben Teixeira


People also ask

Can I store object in IndexedDB?

It lets you store just about anything in the user's browser. In addition to the usual search, get, and put actions, IndexedDB also supports transactions. Here is the definition of IndexedDB on MDN: IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs.

Can you store JSON in a database?

You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database. This article describes the options for storing JSON documents in SQL Server or SQL Database.


1 Answers

var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];

If you are trying to store each OBJECT, then don't stringify it or anything, it is already in perfect form. Change your for() loop to loop through the data objects.

Kristof Degrave had a good point to put these outside of the actual for loop for performance reasons.

    var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE); 
    var objstore = transaction.objectStore(STORE); 

    for (i = 0; i < data.length; i++) { 
        objstore.put(data[i]);
    } 
like image 141
Mark Pieszak - Trilon.io Avatar answered Oct 14 '22 05:10

Mark Pieszak - Trilon.io