javascript 如何在 indexedDB 中存储 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12607251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:39:08  来源:igfitidea点击:

How do I store JSON objects in indexedDB?

javascriptjsonindexeddb

提问by Ruben Teixeira

my return json file looks like this:

我的返回 json 文件如下所示:

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:

没有 JSON.stringify 数据看起来像这样:

[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

但有了它,result.length 不是 5,而是字符串的总字符数,这样我就不能循环了

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

采纳答案by Mark Pieszak - Trilon.io

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.

如果您尝试存储每个 OBJECT,则不要对其进行字符串化或任何其他操作,它已经是完美的形式。更改for()循环以遍历数据对象。

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

出于性能原因,Kristof Degrave有一个很好的观点,将这些放在实际的 for 循环之外。

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

    for (i = 0; i < data.length; i++) { 
        objstore.put(data[i]);
    } 

回答by sandiejat

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

对于新访问者,建议稍作修改:IDBTransaction.READ_WRITE 已被弃用,因此请改用“readwrite”。

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

资源:https: //developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB参考:

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

较旧的实验性实现使用已弃用的常量 IDBTransaction.READ_WRITE 而不是“readwrite”。

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

另外,要减少 loc(我最喜欢),请使用:

var objstore = db.transaction([STORE], "readwrite").objectStore(STORE); 
for (i = 0; i < data.length; i++) { 
    objstore.put(data[i]);
}