10

I am trying to pretty print a JSON from clojurescript, on the browser's console.

I found the following link - How can I pretty-print JSON using JavaScript?

The above link provides the following js - JSON.stringify(obj, undefined, 2)

The following translation in cljs doesnt work (.stringify js/JSON obj undefined 2)

  1. Is there any native way in cljs for pretty printing?
  2. Any ideas why the above cljs expression doesnt work ?
Community
  • 1
  • 1
murtaza52
  • 46,887
  • 28
  • 84
  • 120

5 Answers5

11

UPDATE: ClojureScript now has a full port of clojure.pprint in the form of cljs.pprint.

There's also a fipp which is narrower in scope and likely a bit faster.

dnolen
  • 18,496
  • 4
  • 62
  • 71
  • ClojureScript has two pretty-printers available: https://github.com/shaunlebron/cljs-pprint https://github.com/brandonbloom/fipp – ag0rex May 10 '15 at 19:31
5
cljs.user> (.stringify js/JSON (clj->js {:foo 42}) nil 2)
"{\n  \"foo\": 42\n}"

cljs.user> (pr-str {:foo 42})
"{:foo 42}"
Dustin Getz
  • 21,282
  • 15
  • 82
  • 131
4

The following converts a Clojure map (object) to JSON and prints it in the console as an object that can hence leverage the browsers inspect JSON functionality:

(.dir js/console (clj->js object)) 

EDIT: While pretty printing is really nice, in the developer console I still prefer the ability to browse the data structure as a tree and now frequently use cljs-devtools. It is a library that gives you an interactive data tree that can be expanded as a normal js-object but for vanilla clojure without having to convert to js, meaning :keywords, {:ma "ps"} and the rest of the clj-family.

At the moment it requires you to add a leiningen dependency and some code to your project and to use Chrome Canary.

vikeri
  • 642
  • 6
  • 16
2

clojure.pprint has been ported to ClojureScript with release 0.0-3255. It is called cljs.pprint.

Leon Grapenthin
  • 9,246
  • 24
  • 37
1

Indeed, someone needs to port clojure.pprint, which seems to be going on here shaunlebron/cljs-pprint.

In the mean time, if you are running on NodeJS, I use prettyjson from npm.

(ns foo (:require [cljs.nodejs :as nodejs]
                  [cljs.core :refer [clj->js]]))
(nodejs/enable-util-print!)
(def render (.-render (nodejs/require "prettyjson")))
(defn pp [value] (println (render (clj->js value))))

It then prints the value in colorised YAML:

ClojureScript:foo> (pp {:a 123 :foo ["baz" 42]})
a:   123
foo:
  - baz
  - 42

This is just a hack, but at least is is readable.

wires
  • 4,718
  • 2
  • 35
  • 31