Clojure:
Working with YAML
How to:
Clojure does not include built-in support for YAML, but you can utilize third-party libraries such as clj-yaml
for parsing and generating YAML data. First, add the library to your project dependencies:
;; Add this to your project.clj dependencies
[clj-yaml "0.7.0"]
Here’s how you can use clj-yaml
to parse YAML and convert Clojure maps to YAML.
Parsing YAML:
(require '[clj-yaml.core :as yaml])
;; Parsing a YAML string
(let [yaml-str "name: John Doe\nage: 30\nlanguages:\n - Clojure\n - Python"]
(yaml/parse-string yaml-str))
;; Output:
;; => {"name" "John Doe", "age" 30, "languages" ["Clojure" "Python"]}
Generating YAML from Clojure:
(require '[clj-yaml.core :as yaml])
;; Converting a Clojure map to a YAML string
(let [data-map {:name "Jane Doe" :age 28 :languages ["Java" "Ruby"]}]
(yaml/generate-string data-map))
;; Output:
; "age: 28\nlanguages:\n- Java\n- Ruby\nname: Jane Doe\n"
These simple operations with clj-yaml
can be integrated into Clojure applications to handle configuration files or facilitate data exchange with other services or components that use YAML.