简体   繁体   中英

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);
};   

For new visitors, suggesting a tad of modification: IDBTransaction.READ_WRITE has been deprecated so use "readwrite" instead.

Resource: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB Reference:

Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".

Also, to reduce the loc (which I mostly prefer), use:

var objstore = db.transaction([STORE], "readwrite").objectStore(STORE); 
for (i = 0; i < data.length; i++) { 
    objstore.put(data[i]);
}
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]);
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM