2

Given I have a json file with the contents:

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

How can I parse this file and get the value for each email tag as I need to perform operations using the values.

Example:

Retrieve list of emails

([email protected], [email protected]...)

for each element in the list pass its value to a function. I understand how to pass it to a function, and have come across the get-in function but im not fully sure how to use it in this context.

Optionally, if possible I wish for the file to be stored

[email protected]
[email protected]
...

which will be more practical. I know how to write to a file and such but im not sure how to extract the email data.

2 Answers 2

3

slurp reads the file into a string, then use a JSON parser (e.g. cheshire or data.json) to make it into a vector. If you want to use the second file format, then look at line-seq or split-lines

Sign up to request clarification or add additional context in comments.

6 Comments

I understand how to get the string from a file, I don't understand how to extract each email value from such string
@ChrisEdwards use the JSON parser, then if you're wanting to do something with each of them then use doseq to do so. e.g. (doseq [record (cheshire/parse-string (slurp filename))] (my-function (:email record)))
do you want to post this as an answer so others can find it easier?
@ChrisEdwards I'm still not sure which part you were struggling with. Parsing, iterating through the sequence, or getting the email from the record?
@iterating through the sequence was my issue
|
2

Chris

You can read/parse the file as Dax pointed out and then, to address the other part of your question, once the maps are in a vector:

(def emails (map :email (json/read-str (slurp fully-qualified-file))))

will extract each each email into a sequence. You can then use something like the following to store the emails where each is a 'row' in the resulting file:

(spit fully-qualified-result-file (interpose "\n" emails))

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.