2

What's the best way to store this:

var mydata = [{'11 Alveston Road, Manchester':1},
              {'12 Plymouth Street, Liverpool':2}];

in a cookie to retrieve later?

I can obviously simply turn it all into a text string, and add some symbols as delimiters (hoping that those symbols don't occur anywhere in the data values), but it seems a bit hacky!

Also I'd like to avoid the jQuery cookie plugin etc if possible - I'm working in mobile, and each extra file call is a performance hit.

Thanks!

1
  • Use JSON! Commented May 10, 2011 at 14:39

1 Answer 1

5

This sounds like a job for JSON.stringify:

var myData = JSON.stringify(
    [
        {'11 Alveston Road, Manchester':1},
        {'12 Plymouth Street, Liverpool':2}
    ]
); // "[{"11 Alveston Road, Manchester":1},{"12 Plymouth Street, Liverpool":2}]"

The array is converted into a string in JSON format, which you can then use as the value of your cookie. You can decode it with JSON.parse.


Note: since you are using mobile browsers, they're probably quite modern and so have JSON natively installed. You can use this library to work around this in these cases.

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

Comments

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.