application/octet-stream
•
1.91 KB
•
43 lines
;;; Nujel - Copyright (C) 2020-2021 - Benjamin Vincent Schulenburg
;;; This project uses the MIT license, a copy should be included under /LICENSE
;;;
;;; Contains subroutines for (de-)serializing JSON
(defn tree->json (v)
"Converts a tree into a JSON encoded string, you should prefer VAL->JSON"
(cat "{"
(join (map (tree/keys v)
(fn (k)
(cat "\"" (keyword->string k) "\": "
(val->json (ref v k)))))
",\n")
"}"))
(defn val->json (v)
:export-as serialize
"Return V as a JSON encoded string"
(case (type-of v)
(:nil "null")
((:int :float) (string v))
(:bool (if v "true" "false"))
((:array :pair) (cat "[" (join (map v val->json) ",") "]"))
(:string (string/write v))
(:symbol (cat "\"" (string v) "\""))
(:keyword (cat "\"" (keyword->string v) "\""))
(:tree (tree->json v))
(otherwise (throw (list :type-error "Can't encode the value into JSON" v (current-lambda))))))
(deftest "null" (serialization/json/serialize #nil))
(deftest "123" (serialization/json/serialize 123))
(deftest "123.123" (serialization/json/serialize 123.123))
(deftest "true" (serialization/json/serialize #t))
(deftest "false" (serialization/json/serialize #f))
(deftest "[1,2,3]" (serialization/json/serialize [1 2 3]))
(deftest "[1,true,3.0]" (serialization/json/serialize '(1 #t 3.0)))
(deftest "\"asd\"" (serialization/json/serialize 'asd))
(deftest "\"asd\"" (serialization/json/serialize :asd))
(deftest "\"asd\"" (serialization/json/serialize "asd"))
(deftest "\"asd\"" (serialization/json/serialize "asd"))
(deftest "{\"asd\": null}" (serialization/json/serialize {:asd #nil}))
(deftest "{\"asd\": \"asd\"}" (serialization/json/serialize {:asd :asd}))
(deftest "{\"asd\": 123}" (serialization/json/serialize {:asd 123}))