jsonclojurecompojure

Proper JSON Escaping in Clojure API


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?


Solution

  • 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\"]"