0

I have a simple text file which contains simple email strings such as:

[email protected]
[email protected]
[email protected]
[email protected]

I want to be able to return the contents of this file as a json response through my REST api which is a simple GET request.

Is there a way I can read the file line by line (I can do that) and append to a JSON object such that I can easily render the contents on a webpage.

{
    "emails": [
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ]
}

I want my REST API to look like:

(GET "/emails" [] {
    "emails": [
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ]
})

but I want to render the JSON upon request as the file can be modified.

1
  • Did you define the JSON object itself in your Clojure code? I mean, in terms of Clojure maps/vectors? Commented Jul 24, 2015 at 15:23

2 Answers 2

1

You can use the following:

(GET "/emails" []
     (clojure.pprint/cl-format nil
                               "{\"emails\": [~{~S~^,~}]}"
                               (clojure.string/split-lines (slurp "/path/to/addresses.txt"))))
Sign up to request clarification or add additional context in comments.

1 Comment

Thats almost what im after however is puts the , inside quotes as well so that the result is: {:emails ["[email protected]" "," "[email protected]" "," ...
0

I came up with the following solution using the Chesire library

(GET "/emails" []
    (generate-string {:emails (clojure.string/split-lines (slurp "/path/to/file"))} {:pretty true}))

Comments

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.