I'm writing a chrome extension, and I can't store an array. I read that I should use JSON stringify/parse to achieve this, but I have an error using it.
我正在写一个chrome扩展,我无法存储数组。我读到我应该使用JSON stringify / parse来实现这一点,但是我使用它时出错了。
chrome.storage.local.get(null, function(userKeyIds){
if(userKeyIds===null){
userKeyIds = [];
}
var userKeyIdsArray = JSON.parse(userKeyIds);
// Here I have an Uncaught SyntaxError: Unexpected token o
userKeyIdsArray.push({keyPairId: keyPairId,HasBeenUploadedYet: false});
chrome.storage.local.set(JSON.stringify(userKeyIdsArray),function(){
if(chrome.runtime.lastError){
console.log("An error occured : "+chrome.runtime.lastError);
}
else{
chrome.storage.local.get(null, function(userKeyIds){
console.log(userKeyIds)});
}
});
});
How could I store an array of objects like {keyPairId: keyPairId,HasBeenUploadedYet: false} ?
我怎么能存储像{keyPairId:keyPairId,HasBeenUploadedYet:false}这样的对象数组?
1 个解决方案
#1
27
I think you've mistaken localStorage
for the new Chrome Storage API
.
- You needed JSON strings in case of the localStorage
- You can store objects/arrays directly with the new Storage API
我认为你错误地将localStorage误认为是新的Chrome Storage API。 - 在localStorage的情况下,您需要JSON字符串 - 您可以使用新的Storage API直接存储对象/数组
// by passing an object you can define default values e.g.: []
chrome.storage.local.get({userKeyIds: []}, function (result) {
// the input argument is ALWAYS an object containing the queried keys
// so we select the key we need
var userKeyIds = result.userKeyIds;
userKeyIds.push({keyPairId: keyPairId, HasBeenUploadedYet: false});
// set the new array value to the same key
chrome.storage.local.set({userKeyIds: userKeyIds}, function () {
// you can use strings instead of objects
// if you don't want to define default values
chrome.storage.local.get('userKeyIds', function (result) {
console.log(result.userKeyIds)
});
});
});
#1
27
I think you've mistaken localStorage
for the new Chrome Storage API
.
- You needed JSON strings in case of the localStorage
- You can store objects/arrays directly with the new Storage API
我认为你错误地将localStorage误认为是新的Chrome Storage API。 - 在localStorage的情况下,您需要JSON字符串 - 您可以使用新的Storage API直接存储对象/数组
// by passing an object you can define default values e.g.: []
chrome.storage.local.get({userKeyIds: []}, function (result) {
// the input argument is ALWAYS an object containing the queried keys
// so we select the key we need
var userKeyIds = result.userKeyIds;
userKeyIds.push({keyPairId: keyPairId, HasBeenUploadedYet: false});
// set the new array value to the same key
chrome.storage.local.set({userKeyIds: userKeyIds}, function () {
// you can use strings instead of objects
// if you don't want to define default values
chrome.storage.local.get('userKeyIds', function (result) {
console.log(result.userKeyIds)
});
});
});