Chris Edwards
Chris Edwards

Reputation: 1558

Clojure parse JSON objects and extract specific key

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.

Upvotes: 2

Views: 3567

Answers (2)

Frank C.
Frank C.

Reputation: 8088

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))

Upvotes: 2

Dax Fohl
Dax Fohl

Reputation: 10781

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

Upvotes: 3

Related Questions