javascript 将JSON添加并列出到Cookie中

cnh2zyt3  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(213)

我想把JSON数据添加到浏览器cookie中,然后在DIV中列出添加的JSON数据。但是,我在控制台中得到一个错误。这可能是什么原因,我哪里出错了?

$(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();
 }

控制台:

"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
6xfqseft

6xfqseft1#

我会改变json结构,现在你有[ {{}}, {{}} ]这样的东西,我会把它变成[ {}, {} ]
如果你想保持深度不变,你必须像这样遍历键:

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

相关问题