Storing the JSON Matrix in HTML5 Storage Does Not Work

综合技术 2018-02-11

Here is my HTML code, Here i am storing json Array in localstorage. I want to iterate json later anytime but its showing it undefined. How can i iterate over stored json Array using js ?




var ob=[
   {
     "id":1,
     "name":"one"
   },
   {
     "id":2,
     "name":"two"
   }
];
function clickCounter() {alert("dsdsd");
    if(typeof(Storage) !== "undefined") {
        if (sessionStorage.ob) {
            sessionStorage.ob = ob;
        } else {
            sessionStorage.ob = undefined;
        }

        alert(sessionStorage.ob[0].id);
        for (var i in sessionStorage.ob)
        {
           alert(sessionStorage.ob[i].id);
        }    

    } else {

    }
}





localStorage
, like cookies, is for storing strings
. If you attempt to store a complex object in storage it will first be cast to its string representation.

Therefore, you need to stringify when saving it and parse it back into a complex object when attempting to iterate over it later.

Save:

var obj = {foo: 'bar'};
localStorage.setItem('obj', JSON.stringify(obj)); //<-- saved as JSON string

Read later:

var obj = JSON.parse(localStorage.getItem('obj'));
for (var i in obj) {
    alert(i+' = '+obj[i]); //<-- "foo = bar"
}

您可能感兴趣的

基于 HTML5 WebGL 的 3D 网络拓扑图 在数据量很大的2D 场景下,要找到具体的模型比较困难,并且只能显示出模型的的某一部分,显示也不够直观,这种时候能快速搭建出 3D 场景就有很大需求了。但是搭建 3D 应用场景又依赖于通过 3ds Max 或 Maya 的专业 3D 设计师来建模,Unity 3D 引擎做图形渲染等,这对用户来说都是...
PHP: json_decode on the copyr... I am using PHP 5.2.9-2 with WAMP on a Windows machine. I am having a problem trying to decode a JSON string that contains a copyright symbol in one ...
Print JSON starting with table with SwiftyJSON I am trying to print JSON in Swift 2.0 using SwiftyJSON and Alamofire Alamofire.request(.GET, "http://announcement.vassy.net/api/AnnouncementAPI/Get...
JSON_EQUAL Condition in Oracle Database 18c The JSON_EQUAL condition was introduced in 18c to allow JSON documents to be compared regardless of member order or document formatting. Relat...
JSON with HTTP 原文 Play通过HTTP API与JSON库共同支持内容类型为JSON的HTTP请求和应答。 关于 Controllers, Actions, 和routing的详细资料看 HTTP Programming 我们将通过设计一个简单的RESTful W...