Search code examples
jsonclojure

How to convert a list into JSON in Clojure?


I have a list like below (some sort of ranking data, list is in order):

'(John Kelly Daniel)

and want to convert it into JSON like below:

[{"rank":1, "name":"John"},{"rank":2, "name":"Kelly"},{"rank":3, "name":"Daniel"}]

What would be the easiest and simplest way of doing this using json/write-str at the end?


Solution

  • As a complement for @leetwinski answer (and using their code)

    (ns some-thing.core
      (:require [cheshire.core :refer :all]))
    
    (def names '(John Kelly Daniel))
    
    (defn add-rank [data]
      (map-indexed #(hash-map :rank (inc %1) :name (str %2)) data))
    
    (-> names
        add-rank
        generate-string)