jQuery JSON.stringify没有获取要存储到cookie的整个JSON字符串

时间:2011-03-30 07:21:11

标签: jquery json cookies stringification

我正在尝试使用JSON字符串在Cookie中设置分数......

 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);

警报说:

  

{ “S”: “{分数”:2000, “姓名”: “迈克尔”}}

...而不是整个对象。如何将整个对象变为JSON字符串?

1 个答案:

答案 0 :(得分:3)

这是因为在你的json中你对所有值都使用相同的键,你需要一个数组

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));