Question

I am trying to retrieve the data stored in a cookie. The cookie currently has:

{"Name":"Kevin" "Surname":"Hart" "ImagePath":"Pictures/Kevin/Kevin.jpg" "Age":"18"  n       "Degree":"BSc Computer Science" "Email":"kevin.hart@yahoo.com" "Course":"COS212 65"}

I tried to turn the cookie into an object using JSON.parse() function by doing this:

var studentCookie = document.cookie;
var stuObj =  JSON.parse(studentCookie);

I am not sure if this is how its supposed to be done and at the momemt it does not look like it works. Any help will be appreciated. :)

Was it helpful?

Solution

This should work. Try storing the JSON object as a string inside the cookie. Here's an example of how you can transform the object into a string and vice versa:

$(document).ready(function () { 
    var obj = {"Name":"Kevin", "Surname":"Hart", "ImagePath":"Pictures/Kevin/Kevin.jpg", "Age":"18","Degree":"BSc Computer Science","Email":"kevin.hart@yahoo.com","Course":"COS212 65"};
    console.log(obj);
    var str = JSON.stringify(obj);
    console.log(str);
    document.cookie = "student=" + str;

    var json = JSON.parse(getCookie('student'));
    console.log(json);      
});

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i].trim();
           if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top