Skip to content Skip to sidebar Skip to footer

How Do I Store This Json Object As A Cookie And Than Read It In Vanilla Javascript?

I can actually seem to write it fine as a cookie like this: ['4c3dd477c441e17957000002','4c2ac3cc68fe54616e00002e','4c3dd477c441e17957000003','4c3dd477c441e17957000004'] But how

Solution 1:

Cookies are separated by commas, so when you store the JSON it is being broken up into multiple cookies. You will need to encode the JSON string some way before writing to the Cookie and then decode when reading.

For example, you could take the JSON string and replace the '","' parts like this:

// encode
mycookie = json.replace(/","/g, '"-"');

// decode
json = mycookie.replace(/"-"/g, '","');

Obviously this is no a general solution as you would need to insure that the strings being replaced do not appear in the content (even escaped)

Solution 2:

I think you can just encode like this:

// encode
mycookie = json.replace(/","/g, '"%2C"');

And no modification is needed in decoding

Post a Comment for "How Do I Store This Json Object As A Cookie And Than Read It In Vanilla Javascript?"