2

I have a Clojure function that writes out the contents of a vector of URLs to JSON, and returns this from an API endpoint. This endpoint data is read by an Elm JSON Decoder on a frontend app. Running this Clojure function directly gives me the following:

(json/write-str ["http://www.example.com?param=value" "http://www.example2.com?param=value"])

Which returns:

"[\"http:\\/\\/www.example.com?param=value\",\"http:\\/\\/www.example2.com?param=value\"]"

Wonderful! If I input this result directly into an Elm Decoder such as this:

stringArrayDecoder : Json.Decoder.Decoder (List String)
stringArrayDecoder =
Json.Decoder.list Json.Decoder.string

It parses it happily with no error.

However, when I view the JSON response from the endpoint, it is losing some of the escaping and I get this:

["http:\/\/www.example.com?param=value","http:\/\/www.example2.com?param=value"]

Which my Elm decoder cannot read.

How do I avoid this? How can I get the fully escaped JSON values produced by my internal function through the API endpoint and into my Elm frontend Decoder?

1 Answer 1

4

JSON allows you to escape forward slashes / and other characters as to prevent stuff like </ from popping up in html.

write-str has an :escape-slash boolean option:

:escape-slash boolean

If true (default) the slash / is escaped as \/

Thus you can instead write

(json/write-str ["http://url.one" "http://url.two"] :escape-slash false)
=> "[\"http://url.one\",\"http://url.two\"]"
Sign up to request clarification or add additional context in comments.

4 Comments

Valid workaround - yet i'd like to see this addressed in the elm side if it where my project.
I tried it out and that Elm decoder works... albeit the error > my = Json.Decode.decodeString (Json.Decode.list Json.Decode.string) j Ok ["example.com?param=value","http://… : Result Json.Decode.Error (List String)
Thank you for your help @Remy. I am able to parse the direct output of that updated write-str command as well, though I'm still seeing the issue I mentioned where it's losing the outside double quotes when returned from the API. I may ask a separate question regarding an Elm decoder that will work for the non-quoted JSON array, or better specifying my issue. However your answer was helpful in its own right so I've marked it as such!
Ah ok, now I understand the question better. Maybe the confusion is in what write-str actually does, which is different from what an API would return. I'd suggest you use write instead and build your decoder based on that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.