JS - Beautify json response dynamically loaded in prism.js

43 Views Asked by At

How to "beautify" a json response, after dynamically loaded in prism (https://prismjs.com/docs/Prism.html)? As of right now, I see the json result syntax highlighted in a single row:

    {"status":200,"success":true,"message":"Success! Record(s) available!","data":[{"title":"Item 1"},{"title":"Item 2"}]}

But I would like to have the original ("beautified") structure, so e.g.:

    {
      "status": 200,
      "success": true,
      "message": "Success! Record(s) available!",
      "data": [
        {
          "title": "Item 1"
        },
        {
          "title": "Item 2"
        }
      ]
    } 

That's my setup:

HTML:

    <pre><code class="language-json"></code></pre>

Javascript:

    let code = {
      "status": 200,
      "success": true,
      "message": "Success! Record(s) available!",
      "data": [
        {
          "title": "Item 1"
        },
        {
          "title": "Item 2"
        }
      ]
    };

    console.log(JSON.stringify(code));

    document.querySelector('.language-json').innerHTML = Prism.highlight(JSON.stringify(code), Prism.languages.json, 'json');

And here is a Fiddle: https://jsfiddle.net/80hdf5v9/

1

There are 1 best solutions below

0
UHpi On

As per the official documentation of prismjs the code snippet you want to highlight must be a string enclosed within `<YOUR_CODE>`. I just added the code in `` and removed the JSON.stringify. And this solved the problem.

let code = `{
  "status": 200,
  "success": true,
  "message": "Success! Record(s) available!",
  "data": [
    {
      "title": "Item 1"
    },
    {
      "title": "Item 2"
    }
  ]
}`;

console.log(JSON.stringify(code));

document.querySelector('.language-json').innerHTML = Prism.highlight(code, Prism.languages.json, 'json');

You can see the result at Fiddle: https://jsfiddle.net/kzqfL3sn/