有条件地将外部json加载到localStorage(作为字符串)?

时间:2013-04-24 14:09:20

标签: javascript json getjson

我的测试数据目前在我的html中:

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 },
];

但我的数据最终将是~20,000个条目,所以我希望将它外部化为statusStarter.json文件(本地或外部),我在应用程序首次启动时加载一次。一旦进入客户端localStorage,我可以轻松地在本地读/写! :]另外:

1。如何将外部化的json加载到localStorage(作为字符串)?

2。如何保持条件?(避免每次重新加载)

1 个答案:

答案 0 :(得分:4)

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

给定一个包含以下内容的data.json文件:

[ 
{ "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条件函数,带参数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

读取数据:您的数据现在位于localStorage.myData,作为字符串。您可以使用以下方式访问它:

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

然后更有趣的是写这个本地数据的可能性。