Chrome Extension: StorageArea.Set key being passed as string - javascript

Good evening,
I'm trying to save an associative array into chrome.storage.local, like so:
var keyName = 'name';
var data = //grabbed from an Ajax call
saveData(keyName, data);
function saveData(keyName, data){
console.log("saving with key: "+keyName);
chrome.storage.local.set({keyName:data});
}
To check to make sure the data saved properly, I load:
function loadData(keyName){
console.log("loading: "+keyName);
chrome.storage.local.get(keyName, function(result){
console.log(result);
});
}
The log shows it is trying to load the correct key name, but nothing comes up. I then try calling loadData(null), which will show the entire contents of the local storage, and I find:
Object {keyName: Array[3]}
keyName: Array[3]
__proto__: Object
My data! But the key it saved with is "keyName" instead of "name". The log from saveData outputs that it is "saving with key 'name'", but it's saving with key "keyName" instead...
????
Thanks!

How strange...
Seems my question is similar to Using a variable key in chrome.storage.local.set
The answer they found was to convert the JSON {keyName:data} to an object:
var obj = {};
obj[keyName] = data;
chrome.storage.local.set(obj);
This works.
Is this because the JSON field is automatically passing as a string?

Related

Store JSON to localstorage not working

After pushing a button I would like to save an item (nested JSON) into a new Array and store it to the localstorage.
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.set('favouriteData', this.cardfavouriteArray);
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.get('favouriteData').then((val) => {
console.log('test', JSON.stringify(val));
});
}
I get no error, but 'test' is always empty. I need it as an array.
Set and Get method for localstorage varies on which service you are using
1.HTML5 localStorage- If you are using HTML5 localStorage directly then you should use localStorage.getItem
and localStorage.setItem
2.localstorage is limited to store only string key/value pairs.Use JSON.stringify and JSON.parse when using setting and getting from localstorage
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.getItem('favouriteData').then((val) => {
console.log('test', JSON.parse(val));
});
}
3.ng2-webstorage- In case of ng2-webstorage this.storage.retrieve and this.storage.store will work.
Change this.storage.set('favouriteData', this.cardfavouriteArray); to localStorage.set('favouriteData', JSON.stringify(this.cardfavouriteArray)); (It's a pre-defined method by angular). Also stringify the array.
Set array in local storage like this:
localStorage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
Get array from local storage like this:
var data = JSON.parse(localStorage.getItem('favouriteData'));
Explanation: It is because localstorage can not store object, it stores in string format. So we need to JSON.stringify the object. Also localStorage has function name setItem and getItem as defined here: http://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage. When we get the string from localstorage, we need to JSON.parse to convert it back to object.
You are using this.storage.set and this.storage.get. It is not clear which library are you using, but the code I mentioned will work in Angular or any framework. Since localStorage.setItem and localStorage.getItem is pure javascript.

Accessing a javascript object

I have been working on this problem for quite a while now.
I am defining an array using the following:
let newJsonObject = {
"billing_name": document.getElementsByName("order[billing_name]")[0].value,
"email": document.getElementsByName("order[email]")[0].value,
};
I get the data from storage and keep it in a variable named parsedJson, then do the three following console.log operations:
console.log(parsedJson);
console.log(parsedJson.billing_name);
console.log(parsedJson["billing_name"]);
This first returns an object with the following:
parameters:
{"billing_name": "123", "email": "123"}
However, the following two things logged in the console are undefined.
I have also tried to create the object with the keys not having quotations, but I am still getting undefined
I don't understand why the log is returning null when the object is defined. Does anyone have any suggestions?
EDIT:
Here is how I am storing the data:
chrome.storage.sync.set({"parameters": JSON.stringify(newJsonObject)});
Here is how I am accessing it:
chrome.storage.sync.get("parameters", params => {
if(params === null){
//Nothing is even set, simply return
return;
}else{
//Actually data saved in params
let parsedJson = params;
console.log(parsedJson);
console.log(parsedJson.parameters.billing_name);
console.log(parsedJson["billing_name"]);
Here is a link to what is displayed in console
use JSON.parse converts your json string to object
try this
console.log(JSON.parse(parsedJson.parameters).billing_name);
Try this:
var test = JSON.parse(parsedJson.parameters);
console.log(test.billing_name);
this will work.

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Constructing a valid JSON object with Javascript

I'm using the code below to construct a JSON object that looks like this:
{"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"myemail#hotmail.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_bxx.png"}]};
var data = {};
var contacts;
var gc = $.when(gigya.socialize.getContacts({callback: function(response){
data['contacts'] = response.contacts.asArray();
}}));
gc.done(function(response) {
contacts = data;
});
console.log(contacts);
When I pass the resulting contacts object to Google soy template, the JSON object doesn't seem well constructed.
With the code above, how do I construct a valid JSON object?
Thanks for helping out.
The object seems ok,
try using JOSN.stringify() example jsFiddle
or JSON.parse()
You can see in example, you can turn object into valid JSON and reverse into valid JS object.
Regarding your code
What do you get from response ?
And why do you use response here if you do not make use of it?
gc.done(function(response) {
contacts = data;
});
I would change this line EDITED
data['contacts'] = response.contacts.asArray();
to
contacts = JSON.parse(response.contacts);
and remove
gc.done(function(response) {
contacts = data;
});

Save Javascript file object to local storage

I have a input type file where I save the file to a file object like so
var uploadControl = document.getElementById("fileUpload");
var files = uploadControl.files[0];
Then I would like to save that file to local storage to read into the FileReader object at a later time. Does anyone know if this is possible. I have tried several different options and every time I try and retrieve the object out of local storage, it is undefined.
Here are some things I have tried
var setObj = {"prop": "myProp", "file": files};
chrome.storage.sync.set({"myObj":setObj});
This doesn't throw errors, but when I try and retrieve the object, it is undefined
chrome.storage.sync.get("myObj", function(item) {
console.log("item name: " + item.myObj.file.name);
});
However I can access the other properties of the object
chrome.storage.sync.get("myObj", function(item) {
console.log("item prop: " + item.myObj.prop);
});
Am I doing something wrong when adding the object to local storage or am I accessing it incorrectly? Or is it just impossible to do this?
localStorage can only contain string name/value pairs, which means you can not store an object directly.You can use stringify and parse for that.

Categories

Resources