gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:48:22 24 4
gpt4 key购买 nike

我的测试数据目前在我的 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。如何保持条件?(避免每次都重新加载)

最佳答案

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 +"!");

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

关于javascript - 有条件地将外部 json 加载到 localStorage(作为字符串)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16194203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com