'How do I set JSON data as a cookie while preserving the indentation?

I'm trying to set a cookie containing some JSON data, but I also need to preserve line breaks. I've got a way of keeping them and rendering them which works fine in the console but when I actually put the code in a tag, it doesn't work.

Here's the code:

actualData = JSON.stringify(data.replaceAll("\n", "|")).replaceAll("\\", "");
document.cookie = `data=${actualData}; path=/;`;

Here's the expected input and output, which is in the console:

//input = '[\n    {"content": [\n        {"title": "e"}\n    ]}\n]'
//output = 'data="[|    {"content": [|        {"title": "e"}|    ]}|]"; path=/;'

Here's the input and output when run from a <script> tag:

//input = '[\n    {"content": [\n        {"title": "e"}\n    ]}\n]'
//output = 'data="[\\n    {\\"co|te|t\\": [\\n        {\\"title\\": \\"e\\"}\\n    ]}\\n]"'

I don't understand how the same code is returning a completely different result. I don't know how it gets even worse when flask handles it:

[n    {"content": [n        {"title": "e"}n    ]}n]

Is it something to do with how cookies are handled? Is it something to do with how I'm outputting it?



Solution 1:[1]

you can change your tactic and format the JSON to a string (with the required indentation), then base64 encode the string, store the produced value to the cookie. Then when you receive back the cookie in a subsequent request, you can base64 decode it.

Full example below:

import json
import base64

my_dict = {
    "id": "12345",
    "name": "myname",
    "text": "",
    "list_field": [
        123,
        456,
        "some string"
    ]
}

my_string = json.dumps(my_dict, indent=4)
print(my_string)

my_string_bytes = my_string.encode('ascii')

b64_encoded = base64.b64encode(my_string_bytes)
print(b64_encoded)

b64_decoded = base64.b64decode(b64_encoded)
my_string_decoded = b64_decoded.decode('ascii')
print(my_string_decoded)

if my_string == my_string_decoded:
    print("initial and decoded strings match!")

much cleaner approach, and not prone to unintentional character replacements

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ilias-sp