我想把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: \"undefined\" is not valid JSON", "SyntaxError: \"undefined\" is not valid JSON
at JSON.parse (<anonymous>)
at HTMLDocument.<anonymous> (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
1条答案
按热度按时间6xfqseft1#
我会改变json结构,现在你有
[ {{}}, {{}} ]
这样的东西,我会把它变成[ {}, {} ]
。如果你想保持深度不变,你必须像这样遍历键: