jQuery JSON.stringify not getting the entire JSON string to store to cookie

心已入冬 提交于 2019-12-08 09:06:43

问题


I’m trying to set scores in a cookie with a JSON string…

 var json = JSON.stringify({
   s:{score:2000,name:"Michael"},
s:{score:1000,name:"Tito"},
s:{score:500,name:"Jackie"},
s:{score:100,name:"Marlon"},
s:{score:10,name:"Jermain"}

});
alert(json);
$.cookies.set('highScores',json,30*24);

The alert is saying:

{"s":"{score":2000,"name":"Michael"}}

…and not the entire object. How do I get the whole object to be a JSON string?


回答1:


It is because in your json you are using the same key s for all values you need an array

var scores = [
    {
        score: 2000,
        name: "Michael"
    },
    {
        score: 1000,
        name: "Tito"
    },
    {
        score: 500,
        name: "Jackie"
    },
    {
        score: 100,
        name: "Marlon"
    },
    {
        score: 10,
        name: "Jermain"
    }
];

console.log(JSON.stringify(scores));


来源:https://stackoverflow.com/questions/5483170/jquery-json-stringify-not-getting-the-entire-json-string-to-store-to-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!