pretty-print JSON using JavaScript
#1
I've been working with JSON data a lot lately and I need to output it in a way that's readable for debugging and presentation purposes. The default JSON.stringify gives me a string without any indentation which is tough to read when dealing with nested and complex data structures. I'm looking for a solution that can pretty-print JSON in JavaScript. I've come across JSON.stringify's ability to add indentation but I'm considering additional aesthetics like color-coding keys, values, and even font styles to differentiate between data types at a glance. Does anyone have a robust solution for this?
Ideally, I'm looking for a way to pretty-print JSON that includes:
- Indentation
- Whitespace for readability
- Optional color coding for keys, strings, numbers, booleans, and null values
Something along the lines of:

Code:
json {
    "name": "John Doe",
    "age": 30,
    "isAdmin": false,
    "courses": ["html", "css", "js"],
    "wife": null
}

How can I achieve something like this in a JavaScript environment, possibly for use on a web page or in a Node.js application?
Reply
#2
For pretty-printing JSON with indentation in JavaScript, you can use the JSON.stringify function with its second and third parameters. For example:

Code:
const jsonObject = {
    name: "John Doe",
    age: 30,
    isAdmin: false,
    courses: ["html", "css", "js"],
    wife: null
};
console.log(JSON.stringify(jsonObject, null, 2));

This will print out the JSON with 2 spaces for indentation, which is generally pretty readable. However, for syntax highlighting and colors, you'd need to include some form of HTML and CSS for the web, or use libraries available in Node.js that support colored console output.
Here's a simple browser-based solution involving some HTML and CSS:

Code:
<pre id = "json" > < /pre>


Code:
.key {
        color: red;
    }
    .string {
        color: green;
    }
    .number {
        color: blue;
    }
    .boolean {
        color: magenta;
    }
    .null {
        color: grey;
    }

Then in JavaScript, you'd manually parse the JSON object and wrap elements with spans:

Code:
function syntaxHighlight(json) {
    json = JSON.stringify(json, undefined, 2);
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-fA-F0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|true|false|null|\b-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?\b)/g, function(match) {
        let 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>';
    });
}
document.getElementById('json').innerHTML = syntaxHighlight(jsonObject);

This is a starting point, and it's far from complete. For example, it won't handle all edge cases and will need more detailed handling for complex JSON structures. If you're running this on a Node.js environment, there are modules like 'chalk' or 'colors' that you can use for console output with colors. Would you like to see an example for Node.js as well?
Reply
#3
Yes, that would be ideal. Having a Node.js example would be useful for some server-side script debugging. Do you have a snippet that uses one of those modules you mentioned?
Reply
#4
Sure, the 'chalk' module is quite popular for adding colors to console text. First, you'd need to install the 'chalk' module using npm:

Code:
npm install chalk

After you've installed the module, you can pretty-print your JSON with color like this:

Code:
const jsonObject = {
    // ... your JSON object
};

function prettyPrintJson(json) {
    const jsonString = JSON.stringify(json, null, 2);
    return jsonString.replace(/"(.*?)":/g, chalk.red.bold('$1:') + chalk.white)
        .replace(/: "(.*?)"/g, ': ' + chalk.green('\"$1\"'))
        .replace(/: (true|false)/g, ': ' + chalk.blue.bold('$1'))
        .replace(/: null/g, ': ' + chalk.grey.bold('null'))
        .replace(/: (\d+)/g, ': ' + chalk.magenta.bold('$1'));
}
console.log(prettyPrintJson(jsonObject));

Be aware that chalk will only work in a terminal that supports ANSI color codes; it won't work if you're trying to output colored text on a web page without additional work to convert the styles.
Here's the final working code integrating everything you need:

Code:
const jsonObject = {
    name: "John Doe",
    age: 30,
    isAdmin: false,
    courses: ["html", "css", "js"],
    wife: null
};

function prettyPrintJson(json) {
    const jsonString = JSON.stringify(json, null, 2);
    return jsonString.replace(/"(.*?)":/g, chalk.red.bold('$&') + chalk.white)
        .replace(/: "(.*?)"/g, ': ' + chalk.green('$&'))
        .replace(/: (true|false)/g, ': ' + chalk.blue.bold('$1'))
        .replace(/: null/g, ': ' + chalk.grey.bold('null'))
        .replace(/(\d+)/g, chalk.magenta.bold('$1'));
}
console.log(prettyPrintJson(jsonObject));

This should print your JSON in the terminal with color-coding to increase readability.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)