試圖從字符串中讀取哈希映射,但如果鍵是「關鍵字」類型的值我從cljs.reader/read-string中得到錯誤。從字符串中讀取哈希映射的正確方法是什麼?Clojurescript如何使用數字關鍵字讀取字符串映射?
這個版本不包含關鍵字的工作:
(cljs.reader/read-string (pr-str {1 "a", 1481876814936 "sdafa", 1481876816039 "afdas", 1481876817344 "asdfa", 2 "b"}))
=> {1 "a", 1481876814936 "sdafa", 1481876816039 "afdas", 1481876817344 "asdfa", 2 "b"}
但這個版本的關鍵字拋出一個錯誤:
(cljs.reader/read-string (pr-str {:1 "a", :1481876814936 "sdafa", :1481876816039 "afdas", :1481876817344 "asdfa", :2 "b"}))
cljs.user=> #object[TypeError TypeError: Cannot read property '0' of null]
TypeError: Cannot read property '0' of null
at cljs$reader$read_keyword (file:///test/resources/public/js/ui-out/cljs/reader.js:681:19)
at cljs$reader$read_delimited_list (file:///test/resources/public/js/ui-out/cljs/reader.js:397:20)
at cljs$reader$read_map (file:///test/resources/public/js/ui-out/cljs/reader.js:466:41)
at cljs$reader$read (file:///test/resources/public/js/ui-out/cljs/reader.js:879:34)
at cljs$reader$read_string (file:///test/resources/public/js/ui-out/cljs/reader.js:911:25)
at eval (eval at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8), <anonymous>:1:114)
at eval (eval at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8), <anonymous>:9:3)
at eval (eval at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8), <anonymous>:14:4)
at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8)
nil
相同的代碼工作在Clojure的:
user=> (read-string (pr-str {:1 "a", :1481876814936 "sdafa", :1481876816039 "afdas", :1481876817344 "asdfa", :2 "b"}))
{:1 "a", :1481876814936 "sdafa", :1481876816039 "afdas", :1481876817344 "asdfa", :2 "b"}
如果這些關鍵字是在某些API調用之間生成的,則只需在您的結尾禁用關鍵字轉換即可。數字可以生成很好的鍵如果這是第一個有「奇怪」行爲的地方,其他人會跟隨。 '(關鍵字s)'接受任何東西,你最終可能會破碎的東西。嘗試'(pr-str {(關鍵字「a:b」):c})' – cfrick