Search code examples
clojureseesaw

How can i read string from text file and convert into a map in clojure?


I am trying to use Clojure - Seesaw to read from a file and convert the string into a map (variables) so that I can use them to print to a GUI. Below is my current code:

(ns store.core
(:gen-class)
(:require [seesaw.core :as seesaw]))

(defn -main
  [& args]
  (seesaw/show!

   (spit "amovies.txt" "")
   ;(spit "amovies.txt" (pr-str [{:id 1 :qty 4 :name "movie1" :price 3.50}
   ;                             {:id 2 :qty 5 :name "movie2" :price 3.00}]) :append true)

   (spit "amovies.txt" "movie: Movie_Name\nprice: 5\nid: 1\nquantity: 2" :append true)

   (print (read-string (slurp "amovies.txt")))

   (with-open [rdr (reade "amovies.txt")]
     (doseq [line (line-seq rdr)]
       (println-str line)))

I am stuck figuring out how to read the string from amovies.txt line by line and then create a map with it. The desired output should be something like movie: Movie_Name price: 5 id: 1 quantity: 2

but in a way so that if I were to say, :movie, it would reference the name of the movie.

Can someone help? All help is appreciated!


Solution

  • 1

    (def movies-as-map
      (let [lines (with-open [rdr (reade "amovies.txt")]
                    (line-seq rdr))]
        (binding [*read-eval* false]
          (map read-string lines))))
    

    2

    user> (def movie
            (binding [*read-eval* false]
              (read-string 
               "{:id 1 :qty 4 :name \"movie1\" :price 3.50}")))
    
    #'user/movie
    user> (keys movie)
    (:id :qty :name :price)
    

    Will work with this

    (spit "amovies.txt" 
          (pr-str [{:id 1 :qty 4 :name "movie1" :price 3.50}
                   {:id 2 :qty 5 :name "movie2" :price 3.00}]) 
          :append true)
    

    But not with this

    (spit "amovies.txt" 
          "movie: Movie_Name\nprice: 5\nid: 1\nquantity: 2"
          :append true)
    

    docs: https://clojure.github.io/clojure/branch-master/clojure.core-api.html#clojure.core/read-string

    Wrong args being passed to show!

    It looks like your passing a ton of arguments to seesaw/show!.

    The documentation states

    Usage: (show! targets)

    Show a frame, dialog or widget.

    If target is a modal dialog, the call will block and show! will return the dialog's result. See (seesaw.core/return-from-dialog).

    Returns its input.