Today I put together majority of my Component Cohesion presentation so that I have something to present at lunch and learn tomorrow. But when I started to lose focus on that I switched my focus to learning about .edn (pronounced eden) files, which I’ll have to implement into my tic-tac-toe this week.

What is an EDN file?

EDN (Extensible Data Notation) is a powerful data format native to Clojure, designed to represent data in a human-readable and machine-friendly way. With its minimal syntax and support for complex data structures like maps, lists, and sets, EDN is an excellent choice for configuration files, data interchange, and more.

EDN is similar to JSON but more flexible and extensible. It supports primitive data types like strings, numbers, and booleans, as well as Clojure-specific types like keywords, symbols, lists, vectors, maps, and sets. Here’s an example of an EDN structure:

{:name "Tic-Tac-Toe"
 :players [{:id 1 :name "Alice"}
           {:id 2 :name "Bob"}]
 :settings {:board-size 3
            :win-length 3}}

Reading EDN Files with slurp and edn/read-string

To read data from an EDN file, you can use the slurp function to read the file’s content as a string and then parse it with edn/read-string. Here’s how:

(ns example.core
  (:require [clojure.edn :as edn]))

(defn read-edn-file [file-path]
  (let [file-content (slurp file-path)]
    (edn/read-string file-content)))

(def data (read-edn-file "data.edn"))

In this example, slurp reads the entire file as a string, and edn/read-string converts the string into Clojure data structures.

Writing EDN Files with spit

Writing data to an EDN file is just as easy with spit. The spit function takes a file path and data, converting the data to a string before writing it to the file:

(defn write-edn-file [file-path data]
  (spit file-path (pr-str data)))

(write-edn-file "output.edn" {:foo "bar" :numbers [1 2 3 4 5]})

EDN files, combined with Clojure’s slurp, spit, and edn/read-string functions, provide a powerful yet simple way to work with structured data. Whether you’re building a small script or a large application, EDN’s readability and ease of use make it a great choice for data storage in Clojure.