Search code examples
javascriptjsongetjson

Conditionally load external json into localStorage (as string)?


My test data is currently within my html such :

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 entries, so I wish to externalize it into a statusStarter.json file (local or external), that I load once at the apps first start. Once into the client localStorage I can read/write locally with ease! :] Also:

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

2. How to keep conditional ? (avoid to reload each time)


Solution

  • 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 }
    ]
    

    The JS conditional function, with parametrable 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's firing:
    loadFileJSON( 'myData','http://mywebsite/path/data.json'); 
    // should works w/ local folders as well
    

    Read the data: 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 and more interesting is the possibility to write this local data.