0

So I'm using the JSON.parse-method to retrieve specific data from a cookie. However, if the cookie value does not exist, the input ends. Is there anyway to validate if this data is present before attempting to parse?

actual cookie data : "foo1":"1123","foo2":"332","foo3":"773" 

//function to retrieve cookie
function getCookie(name) {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value !== null) ? unescape(value[1]) : null;
}
var cookie = getCookie("cookiename");
var cookieData = JSON.parse(cookie).foo4;

The code above will give the error unexpected end of input and terminate the program.

Esso
  • 694
  • 4
  • 8
  • 21
Ash
  • 169
  • 1
  • 2
  • 13
  • Console log `cookie` and see what you've got. – adeneo Jul 24 '15 at 10:12
  • This will probably work: `var cookie = getCookie("cookiename") || '[]', which will be decoded into an empty array fi the cookie doesn't exist.` – somethinghere Jul 24 '15 at 10:14
  • *"actual cookie data : "foo1":"1123","foo2":"332","foo3":"773" "* If so, that's not JSON and will not parse. It needs `{` at the beginning and `}` at the end. – T.J. Crowder Jul 24 '15 at 10:14

2 Answers2

1

There are two things you can do, which work well together:

  1. Use a default on cookie in case it's blank

  2. Use error handling around the parse

E.g.:

var cookieData = null;
var foo4;
try {
    cookieData = JSON.parse(cookie || "null");
}
catch (e) {
}
foo4 = cookieData ? cookieData.foo4 : /*appropriate default here*/;

Or if you want the default even if cookieData is there, but it doesn't have foo4 or foo4 is any of the falsey values (null, undefined, 0, "", NaN, or false), that last line would be:

foo4 = cookieData && cookieData.foo4 || /*appropriate default here*/;

Those use JavaScript's curiously-powerful || operator (and it's similarly-powerful && operator) to use "null" rather than cookie if the value of cookie is falsey. But it also uses error handling in case the cookie has complete nonsense in it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • hmm it still doesnt catch an error if foo4 doesnt actually exist in any form – Ash Jul 24 '15 at 11:04
  • @Ash: With the above you won't get an *error*. You'll get `undefined` in the `foo4` variable. I've added a further option that lets you supply the default more aggressively. – T.J. Crowder Jul 24 '15 at 11:32
0

I think you might be asking how to check if the cookie exists, in which case this should help you -

https://stackoverflow.com/a/5968306/2198713

If it's not null then you can go ahead and try and parse it.

To make double sure it's OK, you can wrap your parse in a try block and catch a 'SyntaxError' exception - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Community
  • 1
  • 1