Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda