0

Making a JSON prettifier in pure JavaScript

 1周前 阅读数 0
以下为 快照 页面,建议前往来源网站查看,会有更好的阅读体验。
原文链接: https://ma.ttias.be/making-a-json-prettifier-in-pure-javascript/

Making a JSON prettifier in pure JavaScript

Mattias Geniar, December 20, 2019

Follow me on Twitter as @mattiasgeniar

A few weeks ago I toyed with the idea of making a JSON prettifier myself. I often use these to re-format and debug a minified JSON payload.

I don’t want to trust external web-based tools (and don’t always want to open up an editor to format it), so like most of my projects I decided to write one myself.

And since this is a purely static website, I’m limited to JavaScript.

What I thought would be a fun coding challenge turned out to be … quite boring.

Formatting a JSON body takes just 3 lines of JavaScript.

json = JSON.parse(input);

result = JSON.stringify(json, null, 4);    // stringify with 4 spaces at each level

resultsDiv.innerHTML = result;

This gets the JSON input from a textfield, parses it and through the magic of stringify() it gets pretty-printed straight away.

You can use this tool right here: JSON prettifier. It happens purely client-side and I don’t store any of the input.


Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.


猜你喜欢

关于极客头条


聚合每日国内外有价值,有趣的链接。