Conditionally load external json in localStorage (as a string)?

Currently my test data is in my html, for example:

var jsonStatus = [ { "myKey": "A", "status": 0, score: 1.5 }, { "myKey": "C", "status": 1, score: 2.0 }, { "myKey": "D", "status": 0, score: 0.2 }, { "myKey": "E", "status": 1, score: 1.0 }, { "myKey": "F", "status": 0, score: 0.4 }, { "myKey": "G", "status": 1, score: 3.0 }, ]; 

But my data will eventually be ~ 20,000 records, so I want to urgently allocate it to the statusStarter.json file (local or external), which I upload once at the beginning of the application. Once in the client local storage, I can easily read / write locally !:] Also:

1. How to load external json into localStorage (as a string)?

2. How to keep conditional? (avoid rebooting every time)

+4
source share
1 answer

http://jsfiddle.net/LyAcs/7/

Given a data.json file containing:

 [ { "myKey": "A", "status": 0, "score": 1.5 }, { "myKey": "C", "status": 1, "score": 2.0 }, { "myKey": "D", "status": 0, "score": 0.2 }, { "myKey": "E", "status": 1, "score": 1.0 }, { "myKey": "F", "status": 0, "score": 0.4 }, { "myKey": "G", "status": 1, "score": 3.0 } ] 

JS conditional function with parametric localStorage.target:

 function loadFileJSON( toLocalStorage, fromUrl){ if (localStorage[toLocalStorage]) { console.log("Good! Data already loaded locally! Nothing to do!"); } else { $.getJSON( fromUrl , function(data) { localStorage[toLocalStorage] = JSON.stringify(data); console.log("Damn! Data not yet loaded locally! Ok: I'am loading it!"); }); } } // Function firing: loadFileJSON( 'myData','http://mywebsite/path/data.json'); // should works w/ local folders as well 

Read the data: Now your data is now in localStorage.myData , as a string. You can access it using:

 var myJSON = JSON.parse(localStorage.myData); //Read: alert("Mister " + myJSON[3].myKey + ", your current score is "+ myJSON[3].score +"!"); 

Then the ability to record this local data is more interesting.

+4
source

All Articles