Enhance the appearance of dynamically loaded JSON responses within prism.js using JavaScript

Is there a way to format a JSON response nicely after it has been loaded dynamically in prism ()? Currently, I am seeing the Json syntax highlighted all in one row:

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

What I desire is the original formatted structure like this:

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

This is how my setup looks:

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');

You can also check out a Fiddle with this code here: https://jsfiddle.net/80hdf5v9/

Answer №1

According to prismjs documentation, to highlight a code snippet, it should be enclosed within `<YOUR_CODE>`. I made the necessary adjustments by adding the code in `` and removing JSON.stringify, which successfully resolved the issue.

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 view the outcome on Fiddle: https://jsfiddle.net/kzqfL3sn/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

npm: dealing with white spaces in package.json scripts

Having trouble getting this to work in a package.json file "zip": "C:\\Program Files\\7-Zip\\7z.exe a -tzip -mx9 yes.zip folder\\*" Encountering an error: 'C:\Program\' is not recognized as an ...

Tips for serving images locally instead of using an online URL when exporting with Next.js static:

I've encountered an issue where multiple images pulled from an online source are not being included in my export when I start the process. The image URLs are stored as strings online, but I want them to be saved locally and exported that way instead o ...

Tips for customizing the time selector in material-ui-time-picker

Is there a way to enable keyboard input control for the material-ui-time-picker? Currently, it only allows editing when clicking on the clock interface. Here is a snippet of my code: import React, { Component } from "react"; import { TimePicker } from " ...

Assistance needed with WebSocket and Node.js: Unable to connect to wss://domain:8080 - Issue is not specific to any browser

Greetings, this is my initial inquiry on stack overflow so I'll give it my best shot. Despite going through numerous related questions, I haven't found the solution to my issue. I recently delved into Node.js because I required websockets for ce ...

Is there a way to generate the Table and input the json information using JAVA within CQL?

As a beginner in CQL, I am navigating the world of Cassandra using Docker. In my previous experience, I had two tables named restaurants and Inspection with data inserted via CSV files along with specific settings. Unfortunately, CQL does not support the ...

The type {properties .....} is incompatible with the type ActionReducer<AdminState, Action> in Angular 12 using NGRX

Implementing NGRX library for redux to organize the state of the application in a structured way: export interface ApplicationState { adminState: AdminState } export interface AdminState { adminProductCategory: ProductCategoryState; adminProdu ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

Interacting with a Hapi JS API through a distinct Vue JS Frontend. The data in request.payload is not defined

As I take my first steps on Hapi JS, I am facing the challenge of connecting my app to a SQL Server DB. My current task involves sending login data from a Vue CLI JS frontend to a Hapi JS Api using axios. The login process essentially consists of a "SELEC ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

Regular expression for extracting the initial line only

I'm dealing with a strange string that needs to be manipulated using regular expressions. I am looking for a way to isolate and return only the first line, "Next Business Day", while discarding everything that comes after it. My current attempt looks ...

The jquery datepicker is malfunctioning after switching to another component

My current setup includes the following versions: jQuery: 3.3.1 jQuery UI: 1.12.1 AngularJS: 6 Here's a snippet of my code: <input id="test" type="text" class="form-control" value=""> In my component (component.t ...

Easiest method to change cursor to 'wait' and then return all elements to their original state

On my website, there are certain CSS classes that define a specific cursor style when hovered over. I am trying to implement a feature where the cursor changes to a "wait" image whenever an AJAX call is initiated on any part of the page, and then reverts b ...

Trouble with a basic array duplication function

function duplicateArray(arr) { var len = arr.length; var dup = new Array(); var j; for (j = 0; j < len; j++) { dup[j] = arr[j]; } console.log(dup); } return; duplicateArray([2, 3, 5]); I appreciate your assistance, There are no errors ...

Describe how JSON works

I believe it's important to understand the challenges I'm facing with JSON before I explain my objective: In my work with Google App Engine, I need to store data structured like this: user - username question - question date1 - date1 date2 - da ...

Generating dynamic strings for identifiers in JSX

Can you help me figure out how to dynamically create IDs like this? <div id="track_1"></div> <div id="track_2"></div> I tried assigning the IDs from the parent component like this: export default function Compon ...

Express: when req.body is devoid of any data

My server code using Express: const express = require('express'); const exphbs = require('express-handlebars'); const path = require('path'); const bodyparser = require('body-parser'); const app = express(); cons ...

javascript for transforming date format

My textfield is set to be a date field with a jQuery datepicker(). The dateFormat() is dd-mm-yy, which works perfectly. However, MySQL requires dates to be in yyyy-mm-dd format. I am wondering if I can convert the date format using PHP or JavaScript before ...

Display data in JSON format retrieved from a URL with specific parameters

I'm facing a challenge in displaying specific information from a REST API. JSON data is available for location_ids 2-7, each with its own set of data. How can I efficiently show the data for each location_id individually? Below is the code snippet: ...

Concealing table columns using JavaScript - adapt layout on the fly

I am currently implementing a responsive design feature on my website, where I need to hide certain columns of a table when the viewport size decreases beyond a specific point. Initially, I tried using .style.visibility = "collapse" for all <tr> elem ...

Executing jQuery function through variable reference

My goal is to modify the jQuery function being used based on the value of a switch statement. In this scenario, I want to select the element and then apply the appropriate jQuery function depending on the 'direction' parameter. $('#'+t ...