Wednesday, May 2, 2012

JSON pretty-printing

Today's magic invocation is for pretty-printing JSON strings. If I hit a REST service with my browser, I get back a wad of JSON, which is great, but a bit hard to read. In Chrome (at least), I can pop open the Javascript console and run this:
JSON.stringify(JSON.parse(document.body.children[0].textContent), null, 4)
The JSON is actually displayed by Chrome as text in a <pre> block, which is the only element on the page (child 0 of body). So I have to grab that text, parse it into JSON, and then pretty-print it using stringify (with a 4-space indent). Thanks to Stackoverflow for pointing me in the right direction.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Jekyll Pages List

Getting a list of pages in a Jekyll site is easy, but paring that down to just the top-level files and the index pages is tricky. {% for p...