Pretty-print-json - πŸ¦‹ Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

Overview

pretty-print-json

logo

Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

License:MIT npm Size Vulnerabilities Hits Build

screenshot

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

3) Usage

API

const html = prettyPrintJson.toHtml(data, options?);

Example

HTML:
<pre id=account></pre>
JavaScript:

Pass data into prettyPrintJson.toHtml() 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.
linkUrls boolean true Create anchor tags for URLs.
quoteKeys boolean false Always double quote key names.

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
   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.  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

Comments
  • Add Line number support

    Add Line number support

    Currently, the library doesn't support any type of line number support. We can do hack around the generated output but it would be better to have built-in support for line number

    I am willing to take the issue and work on it. Please let me know your thoughts on it.

    enhancement 
    opened by SomeshThakur 9
  • Undefined import: prettyPrintJson

    Undefined import: prettyPrintJson

    When I import

    import { prettyPrintJson } from 'pretty-print-json';
    

    then prettyPrintJson is undefined. I have no idea why, my IDE IntelliJ has no problems resolving the module and giving type hints.

    This is my tsconfig.json

    {
        "compileOnSave": false,
        "compilerOptions": {
            "target": "es6",
            "module": "esnext",
            "skipLibCheck": true,
            "sourceMap": true,
            "removeComments": true,
            "emitDecoratorMetadata": true,
            "experimentalDecorators": true,
            "allowSyntheticDefaultImports": true,
            "lib": [
                "es2019",
                "dom"
            ],
            "moduleResolution": "node",
            "baseUrl": "src"
        },
    }
    

    I'm using Typescript 3.9.9

    bug 
    opened by mreiche 6
  • Code cleanup, whitespace issues, introduce prettier?

    Code cleanup, whitespace issues, introduce prettier?

    While contributing to this project I noticed that sometimes the whitespace is a bit all over the place. (closing brackets on the same level as the code inside them for example)

    Would you be open to a PR that either:

    • Introduces prettier to keep a consistent format throughout the codebase?
    • Fixes the whitespace issues manually?

    Let me know so I can work on this before you potenitally push a new version (so we do everything at once)

    opened by Pustur 4
  • Make indentation customizable

    Make indentation customizable

    This should resolve issue #2, which called for customizable indentation. I apologize if I missed something obvious as I'm not the keenest on JavaScript, but hopefully I contributed and/or learned something. I tried to conform to the indentation common to the rest of the project. There isn't much else to say about a four-line commit.

    opened by lberrymage 4
  • Switch to trailing comma style in spec/mocha.js

    Switch to trailing comma style in spec/mocha.js

    For multiline arrays and objects, the consistency of including a comma for the last item makes the code easier to edit and helps reduce merge diffs.

    See: https://jshint.com/docs/options/#trailingcomma

    For example, change:

    const input = {
       '$':  'Money',
       'πŸš€': 'Unicode'  //no comma
       };
    

    to:

    const input = {
       '$':  'Money',
       'πŸš€': 'Unicode',  //with comma
       };
    
    help wanted good first issue 
    opened by dpilafian 3
  • Pretty-print json in textareas ?

    Pretty-print json in textareas ?

    Hi,

    I'm doing a tool a send json request and print the response. For this I have 2 textareas where I'd like to pretty print the json typed. As far as I understand, your tool pretty prints the json in pre tags, is it possible to your it to print in textareas ?

    Thanks !

    question 
    opened by niels-hecquard 3
  • Key order not preserved

    Key order not preserved

    I'm using pretty-print-json to print JSON data acquired from web server, but the order of keys displayed by pretty-print-json is not preserved - it prints keys in alphabetical descending order.

    How to print json in original order? Thanks.

    bug 
    opened by zliucd 2
  • Trouble with properly formatting array in JSON object

    Trouble with properly formatting array in JSON object

    I have tried implementing this library correctly but the output I am seeing is not showing my array formatted the way I would like/expect. I have also tried pasting my JSON into your online tool, but the format there is still not what I am needing. The array in the "body" value is still a string. Is there a way to have this library display this array as an array with proper line breaks and indentation?

    image

    Output in my project: image

    opened by jcpage02 2
  • 0.4.3 and 0.4.4 are broken for dynamic import

    0.4.3 and 0.4.4 are broken for dynamic import

    I'm dynamically importing pretty-print-json.

    On versions 0.4.3 and 0.4.4 the loaded object only has a default property, which is an empty object... and has no other properties in the root object or in default. Whereas on 0.4.2 I get this, and it works. image

    opened by softwarecreations 2
  • Change class name

    Change class name "json-value" to "json-number"

    In the HTML output, the value type can only be a number, so number is a more descriptive and accurate name.

    For example, the following:

    <span class=json-value>3.1415</span>
    

    should really be:

    <span class=json-number>3.1415</span>
    
    enhancement help wanted good first issue 
    opened by dpilafian 2
  • Switch to ES6 object method shorthand

    Switch to ES6 object method shorthand

    Upgrade to more modern ES6 function definitions. The newer notation is more compact and looks better.

    See MDN web docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

    enhancement help wanted good first issue 
    opened by dpilafian 2
  • Option to enable more compact layout for small objects and arrays

    Option to enable more compact layout for small objects and arrays

    I've noticed lately that node.js and mongosh are pretty good at not wasting lines when objects have few properties in them. Would be really nice if pretty-print-json could present the stylers arrays on a single line. So using 1 line instead of the 5 lines it currently uses to show the stylers arrays:

        styles: [
            {
              elementType: "geometry",
              stylers: [ { color:'#242f3e' } ],
            },
            {
              elementType: "labels.text.stroke",
              stylers: [ { color:'#242f3e' } ],
            },
            {
              elementType: "labels.text.fill",
              stylers: [ { color:'#746855' } ],
            },
    

    Instead of the current behavior.

    image

    It's very easy to see the number of elements are in an array, or keys in an object. Then doing a sanity check on the line length to determine if it should stay on a single line or spread over multiple lines. So it's very easy to produce a space efficient presentation.

    One way to easily achieve this is if we could pass our own formatting function, so that the lib calls our function with the object(s) and we we format it in some way that the lib understands (spaces on left and newlines, etc) and return it.

    Note I've used:

    • single quotes for improved readability vs double quotes (which weren't necessary because the strings didn't contain single quotes)
    • Spaces between symbols except the colon, when there are multiple keys on a single line I prefer no space around the colon, like { foo:1, bar:2, baz:3 }

    The great thing, is with a callback etc we can style stuff how we like.

    enhancement 
    opened by softwarecreations 2
  • Add JSHint rule to disallow invalid space characters

    Add JSHint rule to disallow invalid space characters

    Configure the project to enforce the JSHint rule that prohibits non-breaking whitespace characters.

    See "jshintConfig" in package.json: https://github.com/center-key/pretty-print-json/blob/master/package.json#L21

    JSHint documentation: https://jshint.com/docs/options/#nonbsp

    help wanted good first issue 
    opened by dpilafian 0
Releases(v1.3.2)
Owner
Center Key
Open source projects
Center Key
✏️ A small jQuery extension to turn a static HTML table into an editable one. For quickly populating a small table with JSON data, letting the user modify it with validation, and then getting JSON data back out.

jquery-editable-table A small jQuery extension to turn an HTML table editable for fast data entry and validation Demo ?? https://jsfiddle.net/torrobin

Tor 7 Jul 31, 2022
JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

Aykut Saraç 20.6k Jan 4, 2023
print faceit elo into the console/chat via telnet

Print MM Ranks and FaceIT elo ingame This tool uses telnet to interact with the console in CS:GO Description Gets faceit elo via the official faceit a

Dominik Wolf 5 Sep 20, 2022
Simple modern JavaScript ES6 library that fetches JSON data into an HTML table which displays nicely within a Bootstrap 4 Card.

Simple modern JavaScript ES6 library that fetches JSON data into an HTML table which displays nicely within a Bootstrap 4 Card. Uses simplenotsimpler/modern-table library.

SimpleNotSimpler 6 Feb 17, 2022
NoPrint.js - Disable Print, Screenshot, Copy & Paste in HTML by JavaScript.

NoPrint.js Disable Print, Screenshot, Copy & Paste in HTML by JavaScript. NoPrint.js is a small and neat open source JS library that disables print, s

null 33 Dec 26, 2022
Random Fractals stash of Observable Data Tools πŸ› οΈ and Notebooks πŸ“š in ES Modules .js, .nb.json, .ojs, .omd, .html and .qmd document formats for Data Previews

Random Fractals stash of Observable Data Tools ??️ and Notebooks ?? in ES Modules .js, .nb.json, .ojs, .omd, .html and .qmd document formats for Data Previews in a browser and in VSCode IDE with Observable JS extension, Quarto extension, and new Quarto publishing tools.

Taras Novak 14 Nov 25, 2022
A lightweight JavaScript library for creating interactive maps and pretty data visualization.

Jsvectormap A lightweight Javascript library for creating interactive maps and pretty data visualization. Explore docs . Report bug Β· View demo Β· Down

Mustafa Omar 204 Dec 24, 2022
Jsonup - This is a zero dependency compile-time JSON parser written in TypeScript

jsonup This is a zero dependency compile-time JSON parser written in TypeScript.

TANIGUCHI Masaya 39 Dec 8, 2022
Data structures & algorithms implementations and coding problem solutions. Written in Typescript and tested with Jest. Coding problems are pulled from LeetCode and Daily Coding Problem.

technical-interview-prep Data structures & algorithms implementations and coding problem solutions. Written in Typescript and tested with Jest. Coding

Lesley Chang 7 Aug 5, 2022
JCS (JSON Canonicalization Scheme), JSON digests, and JSON Merkle hashes

JSON Hash This package contains the following JSON utilties for Deno: digest.ts provides cryptographic hash digests of JSON trees. It guarantee that d

Hong Minhee (ζ΄ͺ 民憙) 13 Sep 2, 2022
Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de crΓ©er un tunnel https pour c

AILI Fida Aliotti Christino 2 Mar 29, 2022
A daily print-and-play roguelike adventure you can play offline.

Chronicles of Stampadia A print-and-play roguelike with a new adventure every day! Play today's adventure | Read the manual | Learn how to play | Disc

Francesco Cottone 36 Oct 15, 2022
Mixed Messages is a simple Node.js application, that will print a randomized fake fact to the terminal each time it is ran.

Mixed Messages - Fake Fact Generator Mixed Messages is a simple Node.js application, That will print a randomized fake fact to the terminal each time

Parietic 2 Jan 10, 2022
A vscode extension to quickly print variable, variable type, tensor shape etc by using shortcuts

Quick Python Print This repo is inspired by "Python Quick Print". "Python Quick Print" can quickly print out variables on the console by using shortcu

weida wang 5 Oct 28, 2022
Print seat layout for movie, flight (jQuery plugin)

seatLayout.js (movie-seat-layout) Print seat layout for movie, flight and seat selection (jQuery plugin) Demo : https://sachinkurkute.github.io/movie-

Sachin Kurkute 20 Dec 8, 2022
πŸ“„ A responsive print preview in A4 format

react-preview-a4 ?? A responsive print preview in A4 format. Table of Contents Installation Examples Demo Installation To install, you can use npm: $

Diagoriente 8 Oct 18, 2022
A Lua plugin, written in TypeScript, to write TypeScript (Lua optional).

typescript.nvim A minimal typescript-language-server integration plugin to set up the language server via nvim-lspconfig and add commands for convenie

Jose Alvarez 315 Dec 29, 2022
Screeps Typescript Starter is a starting point for a Screeps AI written in Typescript.

Screeps Typescript Starter Screeps Typescript Starter is a starting point for a Screeps AI written in Typescript. It provides everything you need to s

null 3 Jan 27, 2022
🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

?? HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Ronen Amiel 1.8k Dec 20, 2022