pretty-print-json
pretty-print-json copied to clipboard
🦋 Pretty-print JSON data into HTML to indent and colorize (with TypeScript declarations)
pretty-print-json
Pretty-print JSON data into HTML to indent and colorize (written in functional TypeScript)
1) Try It Out
Interactive online tool to format JSON:
https://pretty-print-json.js.org
2) Setup
Web browser
Load from the jsdelivr.com CDN:
<link rel=stylesheet href=https://cdn.jsdelivr.net/npm/[email protected]/dist/pretty-print-json.css>
...
<script src=https://cdn.jsdelivr.net/npm/[email protected]/dist/pretty-print-json.min.js></script>
For dark mode, replace pretty-print-json.css
with pretty-print-json.dark-mode.css
in
the <link>
tag.
Node.js server
Install package for node:
$ npm install pretty-print-json
Import into your application:
import { prettyPrintJson } from 'pretty-print-json';
Or for older CommonJS/UMD environments:
const { prettyPrintJson } = require('pretty-print-json'); //deprecated -- use ES modules instead
3) Usage
API
const html = prettyPrintJson.toHtml(data, options?);
Example
HTML:
<pre id=account class=json-container></pre>
JavaScript:
Pass data into prettyPrintJson.toHtml(data, options)
and display the results.
const data = { active: true, mode: '🚃', codes: [48348, 28923, 39080], city: 'London' };
const elem = document.getElementById('account');
elem.innerHTML = prettyPrintJson.toHtml(data);
Options
Name (key) | Type | Default | Description |
---|---|---|---|
indent |
integer | 3 |
Number of spaces for indentation. |
lineNumbers |
boolean | false |
Wrap HTML in an <ol> tag to support line numbers.* |
linkUrls |
boolean | true |
Create anchor tags for URLs. |
quoteKeys |
boolean | false |
Always double quote key names. |
*When setting lineNumbers
to true
, do not use the <pre>
tag as the white-space: pre;
styling is applied to each line (<li>
).
4) TypeScript Declarations
The TypeScript Declaration File file is pretty-print-json.d.ts in the dist folder.
The output of the prettyPrintJson.toHtml(thing: unknown, options?: FormatOptions)
function is
configured with a FormatOptions
object:
type FormatOptions = {
indent?: number, //number of spaces for indentation
lineNumbers?: boolean, //add line numbers
linkUrls?: boolean, //create anchor tags for URLs
quoteKeys?: boolean, //always double quote key names
};
Example TypeScript usage with explicit types:
import { prettyPrintJson, FormatOptions } from 'pretty-print-json';
const data = { active: true, mode: '🚃', codes: [48348, 28923, 39080], city: 'London' };
const options: FormatOptions = { linkUrls: true };
const html: string = prettyPrintJson.toHtml(data, options);
5) Contributor Notes
To be a contributor, fork the project and run the commands npm install
and npm test
on your
local clone.
To see some example HTML results, run node spec/examples.js
.
Make your edits and rerun the tests. Pull requests welcome.
Feel free to submit questions at:
github.com/center-key/pretty-print-json/issues
MIT License | Blog post