Skip to content
Fix Code Error

pretty-print JSON using JavaScript

March 13, 2021 by Code Error
Posted By: Anonymous

How can I display JSON in an easy-to-read (for human readers) format? I’m looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

Solution

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(s*:)?|b(true|false|null)b|-?d+(?:.d*)?(?:[eE][+-]?d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(s*:)?|b(true|false|null)b|-?d+(?:.d*)?(?:[eE][+-]?d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
Answered By: Anonymous

Related Articles

  • error LNK2005: ✘✘✘ already defined in…
  • Reference - What does this regex mean?
  • How do I keep only the first map and when the game…
  • Convert array to nested JSON object - Angular Material tree
  • Creating a singleton in Python
  • Python is not calling fucntions properly
  • Validate that a string is a positive integer
  • Active tab issue on page load HTML
  • Unresponsive hamburger icon in HTML
  • Keeping the User logged in
  • Making Make Automatically Compile Objs from Headers…
  • How to use html template with vue.js
  • How to check if a string contains text from an array…
  • Adobe XD to responsive html
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • PHP parse/syntax errors; and how to solve them
  • What does this symbol mean in JavaScript?
  • How to use if else if in button - flutter
  • Is it possible to apply CSS to half of a character?
  • SVG. Center the text inside tag
  • SQL query return data from multiple tables
  • problem with client server unix domain stream…
  • Convert JavaScript string in dot notation into an…
  • How do the PHP equality (== double equals) and…
  • How to show title in hover - css / jquery
  • What are the undocumented features and limitations…
  • Backgrid filter not working in backbone app
  • regex match any single character (one character only)
  • How to add fonts to create-react-app based projects?
  • What is and how to fix…
  • How can I extract embedded fonts from a PDF as valid…
  • Matplotlib scatter plot legend
  • Get the name of an object's type
  • How do I observe sub-property changes in Polymer?
  • Why adding a criteria in for loop significantly…
  • Smart way to truncate long strings
  • Azure Sql : Unable to Replace HTML String
  • How to pass TypeScript constants to Vue templates…
  • Perfomance issues with large number of elements in…
  • Current time formatting with Javascript
  • Jquery fadeToggle Trouble
  • Adding Input Value Into An Object (Vue.js)
  • Self-hosted fonts using NextJS
  • How to make a class property?
  • Mismatch Detected for 'RuntimeLibrary'
  • Wrong response from controller JSP
  • How can I parse a CSV string with JavaScript, which…
  • How to make a Vue plugin function call methods on…
  • Having trouble with my nav bar/header, It used to…
  • Why my "title" bloc doesn't go to bottom?
  • How does the "this" keyword work?
  • Font is loaded but not applicated
  • Filter data in DataTable Flutter
  • JavaScript - How to have collision with character…
  • Centering in CSS Grid
  • What is the scope of variables in JavaScript?
  • How to resolve…
  • My submit button is not getting enabled . How do i do that?
  • R: "Unary operator error" from multiline ggplot2 command
  • How to create a game over screen for a basic HTML/JS game?
  • How to use Regular Expressions (Regex) in Microsoft…
  • Issue: C compiler used for C++ in CMake | CMake + git
  • What is an optional value in Swift?
  • How to initialize a list with constructor?
  • data.table vs dplyr: can one do something well the…
  • How to serialize SqlAlchemy result to JSON?
  • error LNK2038: mismatch detected for '_MSC_VER':…
  • TypeScript metadata reflection references other…
  • Data binding between two Polymer elements using polymer 1.0
  • How to use Font Awesome 5 icons in Element UI
  • Named colors in matplotlib
  • Programmatically Lighten or Darken a hex color (or…
  • How do I correctly clone a JavaScript object?
  • Swift extract regex matches
  • Reset/remove CSS styles for element only
  • Can't understand the difference between declaring a…
  • Test for existence of nested JavaScript object key
  • HTTP Status 500 - org.apache.jasper.JasperException:…
  • How to find Control in TemplateField of GridView?
  • Lua inheritance and methods
  • Reversing a string in C
  • How to make Javascript font responsive?
  • How to convert to px?
  • Playing HTML5 video on fullscreen in android webview
  • How do I expand the output display to see more…
  • LNK2019 símbolo externo public: bool __thiscall ……
  • Aurelia, navigate is not updating viewport
  • javascript .replace and .trim not working in vuejs
  • How are people implementing immutable data…
  • How to check if a string contains only digits in Java
  • Flutter - Insert a Listview between two fixed containers
  • Logging best practices
  • How do i update a javascript variable as its value changes?
  • Webpack build error
  • how to create separate box for each category in flutter
  • Use of String.Format in JavaScript?
  • open telemetry InMemorySpanExporter not reseting…
  • Create HTML with inline CSS(including color, font…
  • How to change the color of vaadin-select-text-field…
  • What does a "Cannot find symbol" or "Cannot resolve…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Show/hide ‘div’ using JavaScript

Next Post:

Make iframe automatically adjust height according to the contents without using scrollbar?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error