Skip to content

Commit 75e7db7

Browse files
committed
Add pixie.data.json for reading and writing JSON
1 parent 1fc072b commit 75e7db7

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

pixie/data/json.pxi

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
(ns pixie.data.json
2+
(:require [pixie.parser.json]
3+
[pixie.string :as string]))
4+
5+
(def read-string pixie.parser.json/read-string)
6+
7+
(defprotocol IToJSON
8+
(write-string [this]))
9+
10+
(defn- write-map [m]
11+
(if (empty? m)
12+
"{}"
13+
(str "{ "
14+
(->> m
15+
(map (fn [[k v]] (string/interp "$(write-string k)$: $(write-string v)$")))
16+
(string/join ", "))
17+
" }")))
18+
19+
(defn- write-sequential [xs]
20+
(if (empty? xs)
21+
"[]"
22+
(str "[ "
23+
(->> (map write-string xs)
24+
(string/join ", "))
25+
" ]")))
26+
27+
(defn- write-str [s]
28+
(string/interp "\"$s$\""))
29+
30+
(extend-protocol IToJSON
31+
Character (write-string [this] (write-str this))
32+
Cons (write-string [this] (write-sequential this))
33+
EmptyList (write-string [this] (write-sequential this))
34+
Number (write-string [this] (str this))
35+
Keyword (write-string [this] (write-str (name this)))
36+
LazySeq (write-string [this] (write-sequential this))
37+
IMap (write-string [this] (write-map this))
38+
IVector (write-string [this] (write-sequential this))
39+
Ratio (write-string [this] (str (float this)))
40+
String (write-string [this] (write-str this)))
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
(ns pixie.tests.data.test-json
2+
(:require [pixie.test :refer :all]
3+
[pixie.data.json :as json]))
4+
5+
6+
7+
;; This test just ensures that we can use read-string; more thorough testing is
8+
;; done in pixie.tests.parser.test-json
9+
(deftest test-read-string
10+
(assert= (json/read-string "{\"foo\": 42, \"bar\": [\"baz\"]}")
11+
{"foo" 42, "bar" ["baz"]}))
12+
13+
(deftest test-write-string
14+
(assert= (json/write-string {:strings {:a \a, :b "b", :c "", :d :d}
15+
:numbers {:one 1, :two 2.0, :three 3/1}
16+
:lists {:empty {:vector [], :list '(), :seq (take 0 (range))}
17+
:non-empty {:vector [1 2 3], :list '(1 2 3), :seq (take 3 (range))}}
18+
:maps {:empty {}, :non-empty {:this "is covered, right? ;)"}}})
19+
"{ \"strings\": { \"b\": \"b\", \"c\": \"\", \"a\": \"a\", \"d\": \"d\" }, \"maps\": { \"non-empty\": { \"this\": \"is covered, right? ;)\" }, \"empty\": {} }, \"lists\": { \"non-empty\": { \"seq\": [ 0, 1, 2 ], \"list\": [ 1, 2, 3 ], \"vector\": [ 1, 2, 3 ] }, \"empty\": { \"seq\": [], \"list\": [], \"vector\": [] } }, \"numbers\": { \"one\": 1, \"two\": 2.000000, \"three\": 3 } }"))

0 commit comments

Comments
 (0)