Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!