export Data in localStorage for later re-import - javascript

I want to export a few items from my localStorage to save it externally but in a format so that I can import it again later.
My attempt was to write executable code that can be pasted later in a textarea. Then the value of that textare will simply be eval()ed.
Problem: The data stored in localStorage were stored as
var data = [];
data.push('sampledata');
data.push({sample: 'object'});
localStorage.setItem('varname',data);
So it contains various chars I don't like, like ', " etc
My (not working) solution so far was:
var container = $('#localDataContainer');
container.append('localStorage.setItem("cockpitLastVisited","' + localStorage.getItem("cockpitLastVisited") + '");<br/>');
container.append('localStorage.setItem("cockpit_services","' + localStorage.getItem("cockpit_services") + '");<br/>');
container.append('localStorage.setItem("cockpit_users","' + localStorage.getItem("cockpit_users") + '");');
If my attempt seems to be OK, what is the best way to create code that can then be executed the way it is?

Here's how to import/export your entire localStorage
Export
copy(JSON.stringify(localStorage));
This will copy your localStorage to your clipboard. (You need two JSON.stringify()'s to get the quotes escaped.)
Import
var data = JSON.parse(/*paste stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
localStorage.setItem(k, JSON.stringify(data[k]));
});

Just an improved version of Jeremy. To simplify the process
copy('var data = '+JSON.stringify(localStorage)+';Object.keys(data).forEach(function (k){localStorage.setItem(k, data[k]);});');
Run this in console where you need to export, it copies localstorage content along with code to clipboard and just paste it in the console where you want to import.

You can encode Objects into Strings using JSON.stringify (object to String) and decode Strings into Objects using JSON.parse (String to Object).
Write to localStorage
localStorage.setItem("varname",JSON.stringify(originalVarname));
Read from localStorage
var originalVarname= JSON.parse(localStorage.getItem("varname"));

Export
copy(JSON.stringify(JSON.stringify(localStorage)));
Import
var data = JSON.parse(/*previously copied stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
localStorage.setItem(k, data[k]);
});

Just a modernized version of #iceLord answer.
Just run this in the console, it will put the code to restore the localStorage back into your clipboard.
copy(`Object.entries(${JSON.stringify(localStorage)})
.forEach(([k,v])=>localStorage.setItem(k,v))`)
Bookmarklet version
javascript:prompt(`localStorage from ${location.host}${new Date().toLocaleString()}`, `/* localStorage from ${location.host}${new Date().toLocaleString()}*/Object.entries( ${JSON.stringify(localStorage)}).forEach(([k,v])=>localStorage.setItem(k,v))`)

Related

How to append an item to a JSON stored in a file?

Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Here is the code:
Thanks.
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
Read file content.
Parse JSON text into an object.
Update the object in memory.
Write object in JSON format back to the file system.
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

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.

load JSON with JQuery

Is it possible to load JSON file once, and in further call will use loaded JSON (for ex. from cache)?
The easiest way to achieve this is to use the localStorage of JavaScript.
Let's assume you have an object named object.
You can store it this way:
// parse Object to JSON, then store it.
let jsonObject = JSON.stringify(object);
localStorage.setItem('myObject', jsonObject);
And if you want to use it again, do it this way:
// load it from storage and parse the JSON to Object.
let jsonObject = localStorage.getItem('myObject');
let object = null;
if(jsonObject){
object = JSON.parse(jsonObject);
}
Then change it according to your needs and store it again.
You can delete it by
localStorage.removeItem('myObject');
There are so many ways,
You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778
You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778
For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html
For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/

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