Home > Software design >  Adding and listing JSON to the cookie
Adding and listing JSON to the cookie

Time:11-27

I want to add JSON data to the browser cookie and then list the added JSON data in a DIV. However, I am getting an error in the console. What could be the reason for this and where am I going wrong?

$(document).ready(function() {
   var obj = [{
     "file-postSender_revize1.png": {
       "asrs": "gi",
       "name": "postSender_revize1.png",
       "life": "48",
       "type": "parcel"
     }
   },{
     "file-postSender_revize2.png": {
       "asrs": "gi",
       "name": "postSender_revize2.png",
       "life": "24",
       "type": "parcel"
     }
   }];

   document.cookie = "uploadFiles="   obj;
   var str = JSON.stringify(getCookie('uploadFiles'));
   var json = JSON.parse(str);
   for (var i = 0; i < json.length; i  ) {
     document.getElementById('fileList').innerHTML  = json[i].name;
   }

 });

 function getCookie(name) {
   const value = `; ${document.cookie}`;
   const parts = value.split(`; ${name}=`);
   if (parts.length === 2) return parts.pop().split(';').shift();
 }

Console:

"jQuery.Deferred exception: \&quot;undefined\&quot; is not valid JSON", "SyntaxError: \&quot;undefined\&quot; is not valid JSON
    at JSON.parse (&lt;anonymous&gt;)
    at HTMLDocument.&lt;anonymous&gt; (https://fiddle.jshell.net/_display/?editor_console=true:124:20)
    at mightThrow (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js:3557:29)
    at process (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js:3625:12)", undefined

CodePudding user response:

I would change the json structure, right now you have something like [ {{}}, {{}} ], and i would make [ {}, {} ]

If you want to keep the depth as is, you will have to iterate over the keys like so :

Object.keys(json[i]).forEach(k => { 
   console.log(json[i][k].name) 
})
  • Related