pretty-print-json
Pretty-print JSON data into HTML to indent and colorize (written in functional TypeScript)
A) Try It Out
Interactive online tool to format JSON:
https://pretty-print-json.js.org
B) Setup
1. Web browser
Load from the jsdelivr.com CDN:
<link rel=stylesheet href=https://cdn.jsdelivr.net/npm/pretty-print-json@1.2/dist/pretty-print-json.css>
...
<script src=https://cdn.jsdelivr.net/npm/pretty-print-json@1.2/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.
2. 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
C) Usage
1. API
const html = prettyPrintJson.toHtml(data, options?);
2. 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);
3. 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>
).
D) 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);
E) 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