0

I am using readJSON which, in case of error, yields Left err. Sometimes this error (a string) contains quotation marks, e. g. ReferenceError: "JSON" is not defined. I need to return this error wrapped in a JSON string, sort of like

Left err -> "{ \"error\" : \"The error is: " ++ (show err) ++ "\" }"

(the show is needed because we are in a fail monad.)

But when err has quotation marks like the example above, this rips the JSON apart. How to get this working?

(In PSCI, show seems to do a good job of escaping things, e. g. show "\"foo\"" yields a fireworks of \. But inside a function as above, not?)

0dB
  • 675
  • 5
  • 13
  • You should not build your JSON with string concatenation. Use `JSON.stringify`, which will handle the encoding. *edit:* I assume pursescript has that as well, or something similar. – Felix Kling Apr 25 '16 at 17:38
  • Thanks. You wouldn’t happen to know how to do that in PureScript, would you? (I am not a JS expert.) I can build a JSON *object*, but the calling function (Java / Rhino) expects a string back. – 0dB Apr 25 '16 at 17:40

2 Answers2

2

You might be better off using purescript-argonaut rather than purescript-foreign for your use case here. If you show an argonaut JSON value it will use JSON.stringify to produce the value.

gb.
  • 4,629
  • 1
  • 20
  • 19
  • Thanks, I was not aware that there are alternatives. So far my code relies on `purescript-foreign`. I might look into what it means to change that or to use a mix, meaning using `purescript-argonaut` just for that one case. – 0dB Apr 28 '16 at 08:10
  • See also my comment to the answer by @Christoph Hegemann: I think this is a generic issue not necessarily related to JSON. I think it has to do with `show` in PureScript or some other way of taking care of quotes when concatenating strings. – 0dB Apr 28 '16 at 16:12
0

The "lightweight" way would be to call Global.Unsafe.unsafeStringify which is just an FFI call to JSON.stringify. If this happens more often you're better of using Argonaut as @gb said though.

Christoph Hegemann
  • 1,434
  • 8
  • 13
  • I’m wondering: Isn’t my question a general one, one of concatenating two strings, one of which having quotes that need to be escaped? (I’m not sure if this is a JSON issue at all.) – 0dB Apr 28 '16 at 14:18
  • A string is a completely valid piece of JSON on its own. I think your question is more about serializing strings, which in js world is done using JSON.stringify. – Christoph Hegemann Apr 28 '16 at 19:58