acdlite / acdlite/flummox

Double backslashes on double quotes in serialized Flux state?

Abierto
#174 8 comentarios 0 reacciones 0 asignados Ver en GitHub
outdated question
Lenguaje dominante
JavaScript
Estrellas
1.7k
Forks
109
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

Hey

I have a simple store that serializes plain JS objects like so,

``` js
export default class ProjectStore extends Store {
static serialize (state) {
return JSON.stringify(state);
}
static deserialize (stateString) {
return JSON.parse(stateString);
}
...etc
}
```

And when I call my flux's serialize method server side I get a string somewhat like this (the escaped quotes being due to the fact that first I stringify the store and then you stringify the whole store tree, effectively double stringifying some parts of the output),

``` js
{"project":"{\"id\":\"7c5b02f7f4c80b2a5327aba1c3000c9a\",\"title\":\"Jolly trip\"}"}
```

I put this string into my app template (using Handlebars) and it ends up rendered on the page something like,

``` html

var stateString = '{"project":"{\"id\":\"7c5b02f7f4c80b2a5327aba1c3000c9a\",\"title\":\"Jolly trip\"}"}'

```

The problem is that when I call `flux.deserialize(stateString)` in the client it chokes on it, specifically `JSON.parse` throws a wobbly. Afaiu this is because by the time `stateString` has been parsed into a string literal JS has striped out the backslashes (as expected), so that when I print it out in the console it looks like,

``` js
"{"project":"{"id":"7c5b02f7f4c80b2a5327aba1c3000c9a","title":"Jolly trip"}"}"
```

I don't really know what's going on there, aside from the fact that `JSON.parse` doesn't like it at all.

Now, I can fix this by doubling up on the backslashes server side before rendering the string into the template. Doing something like this,

``` js
let stateString = flux.serialize();
stateString = stateString.split('\\').join('\\\\');
```

Which results in rendered template,

``` html

var stateString = '{"project":"{\\"id\\":\\"7c5b02f7f4c80b2a5327aba1c3000c9a\\",\\"title\\":\\"Jolly trip\\"}"}'

```

The above string feeds into `flux.deserialize()` quite happily and gets parsed properly and the app state recreated.

Just wondering if you've come across this sort of thing before? Have you found yourself double escaping backslashes, is it the right way to go or am I being thick?

Thanks!

Great package btw! :)

Guía de contribución

Abrir la guía de contribución

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.