Clojure – Libraries

Clojure libraries

In this guide, we will discuss Clojure Libraries. One thing which makes the Clojure library so powerful is the number of libraries available for the Clojure framework. We have already seen so many libraries used in our earlier examples for web testing, web development, developing swing-based applications, the jdbc library for connecting to MySQL databases. Following are just a couple of examples of few more libraries.

data.xml

This library allows Clojure to work with XML data. The library version to be used is org.clojure/data.xml “0.0.8”. The data.xml supports parsing and emitting XML. The parsing functions will read XML from a Reader or InputStream.

Example

Following is an example of the data processing from a string to XML.

(ns clojure.examples.example
   (use 'clojure.data.xml)
   (:gen-class))
(defn Example []
   (let [input-xml (java.io.StringReader. "<?xml version = \"1.0\"
      encoding = \"UTF-8\"?><example><clo><Adglob>The Adglob
      value</Adglob></clo></example>")]
      (parse input-xml)))

#clojure.data.xml.Element{
   :tag :example, :attrs {}, :content (#clojure.data.xml.Element {
      :tag :clo, :attrs {}, :content (#clojure.data.xml.Element {
         :tag :Adglob, :attrs {},:content ("The Adglob value")})})}
(Example)

data.json

This library allows Clojure to work with JSON data. The library version to be used is org.clojure/data.json “0.2.6”.

Example

Following is an example on the use of this library.

(ns clojure.examples.example
   (:require [clojure.data.json :as json])
   (:gen-class))
(defn Example []
   (println (json/write-str {:a 1 :b 2})))
(Example)

Output

The above program produces the following output.

{\"a\":1,\"b\":2}

data.csv

This library allows Clojure to work with ‘csv’ data. The library version to be used is org.clojure/data.csv “0.1.3”.

Example

Following is an example on the use of this library.

(ns clojure.examples.example
   (require '[clojure.data.csv :as csv]
      '[clojure.java.io :as io])
   (:gen-class))
(defn Example []
   (with-open [in-file (io/reader "in-file.csv")]
      (doall
      (csv/read-csv in-file)))
   (with-open [out-file (io/writer "out-file.csv")]
   (csv/write-csv out-file
      [[":A" "a"]
      [":B" "b"]])))
(Example)

In the above code, the ‘csv’ function will first read a file called in-file.csv and put all the data in the variable in-file. Next, we are using the write-csv function to write all data to a file called out-file.csv.

Learn More : Click Here

This Post Has 2 Comments

Leave a Reply