1

I'm currently processing some json encoded data, but I can't access it properly, this are some tests I did:

Code fragment 1:

var json = [
{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},
{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}];
console.log(json[0][0]);

outputs:

1

Code fragment 2:

var json2 = getCookie('markers');
console.log(json2[0][0]);

outputs:

[

Code fragment 3:

console.log(getCookie('markers'));

output:

[{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}]

as you can see when I use the result from test 3 hardcoded I can access it fine, but when I use it only in code i get something diffrent

does anyone know how to do this?

2 Answers 2

5

Cookies only store strings. You need to use JSON.parse() to convert them back to an object. Also, the contents of json isn't JSON but a JAvaScript object (actually, an array).

var obj2 = JSON.parse(getCookie('markers') || '[]');
console.log(obj2[0][0]);

The || '[]' falls back to an empty array if the cookie is missing since an empty string or undefined wouldn't be valid JSON.

Sign up to request clarification or add additional context in comments.

2 Comments

([])[0][0] will gives TypeError: Cannot read property '0' of undefined
True, in the example it'll fail. But in his actual code he probably won't just blindly access that element.
1

The getCookie('markers') returns string. The native javascript method JSON.parse(text[, reviver]) , parse a string as JSON.

 var json2 = getCookie('markers');
 if ( typeof(json2 ) == "string" ) {
      json2 = JSON.parse( json2 );  
 }

Then try your code ..

2 Comments

When would you expect the cookie not to be a string? Wouldn't it make more sense to handle empty cookies for this value in a more transparent way?
@rlemon I know that .. but in question there less informtion about getCookie method . Thanks for pointing out that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.