Tips for showcasing unprocessed JSON information on a webpage

Similar Question:
JSON pretty print using JavaScript

I am looking to present my raw JSON data on an HTML page similar to how JSONView displays it. Here is an example of my raw JSON data:

{
   "hey":"guy",
   "anumber":243,
   "anobject":{
      "whoa":"nuts",
      "anarray":[
         1,
         2,
         "thr<h1>ee"
      ],
      "more":"stuff"
   },
   "awesome":true,
   "bogus":false,
   "meaning":null,
   "japanese":"明日がある。",
   "link":"http://jsonview.com",
   "notLink":"http://jsonview.com is great"
}

This data is sourced from . What I aim to accomplish is similar to when using Chrome with the JSONView plugin installed.

I have attempted to understand the process but have not succeeded. I am looking to use a JavaScript script (with CSS for formatting) to customize the display of my raw JSON data retrieved via AJAX and then place it on an HTML page within a specified element like a div. Are there any JavaScript libraries available to achieve this task, or could you provide guidance on how to achieve this?

Answer №1

To display JSON data on an HTML page, you can easily use JSON.stringify.

For instance, if your JSON is structured like this:

var jsonData = {
        text: "example",
        number: 1
    };

You can convert it to a string with this simple code:

var jsonString = JSON.stringify(jsonData);

Then you can directly insert it into your HTML code, like so:

document.body.innerHTML = jsonString;

Consider replacing body with another element using getElementById.

Regarding the CSS aspect, you have the option to use RegExp to modify the stringified object before placing it in the DOM. For illustration, the code snippet provided should handle the formatting of curly braces (also available on JSFiddle for demonstration).

var jsonData = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonString = JSON.stringify(jsonData),  // THE OBJECT STRINGIFIED
    formattedString = '', // AN EMPTY STRING TO STORE THE FORMATTED OBJECT STRING
    tracker = {
            brace: 0
        }; // AN OBJECT TO TRACK INCREMENTS/DECREMENTS,
           // MAINLY FOR CURLY BRACES (COULD ADD MORE PROPERTIES)

formattedString = jsonString.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (match, p1) {
var returnFunc = function() {
        return '<div style="text-indent: ' + (tracker['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    returnString = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        returnString = returnFunc();
        tracker['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         tracker['brace'] -= 1;
        returnString = returnFunc();
    } else {
        returnString = returnFunc();
    }
    return returnString;
});

document.body.innerHTML += formattedString; // appends the result to the HTML document body

This code segments the object sections within the string and organizes them into div elements. It adjusts indentation when encountering curly braces, similarly to the 'space' argument in 'JSON.stringify'. You can adapt this as a foundation for different formatting styles.

Answer №2

Keep in mind that the link you shared is not an HTML page, but rather a JSON document. The browser takes care of the formatting.

You need to decide:

  1. Whether you prefer displaying the raw JSON (not in an HTML page), similar to your example
  2. To showcase an HTML page with formatted JSON

If you choose option 1, instruct your application to present a response body with the JSON, specify the MIME type (application/json), and so forth. The browser (and/or browser plugins) will handle the formatting in this scenario.

For option 2, it involves creating a basic HTML page with the JSON content that can be highlighted in various ways:

  • On the server-side, depending on your technology stack. There are solutions available for almost every programming language.
  • On the client-side using JavaScript highlight libraries.

Providing more information about your technology stack will make it easier to offer examples or resources.

EDIT: If you opt for client-side JS highlighting, you might want to consider using highlight.js.

Answer №3

Embedding JSON in an HTML tag other than the <script> tag simply results in plain text. It's like adding a little narrative to your HTML page.

However, when it comes to styling and formatting, that's a whole different story. Perhaps consider changing the title of your query.

Check out this question for more insights. You can also visit this page for additional information.

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

Having trouble retrieving responseText from an AJAX request using Laravel

I am facing an issue with my AJAX call setup. Here is how it looks: function getPosts(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.po ...

There is an error message in Vue nextTick: "TypeError: this.method is not a function." The error only appears in my console, but the functionality seems to be working correctly in the browser

I'm experiencing an issue where I encounter an error when accessing a certain component for the second time in my browser. The strange thing is that everything appears to be working fine initially, but the error occurs when I try to perform actions li ...

"Conceal and reveal dynamic content using the power of jQuery's

Hello everyone, I'm encountering an issue with this code where I am trying to display a variable in the content. Take a look at the code below: I am attempting to show the variable $name in the div #divToToggle upon clicking, but the variable does no ...

What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to m ...

Exploring the utilization of functions beyond module exports

Striving to clearly communicate my intentions, please feel free to ask if anything is unclear. Within a file named www, I am configuring my socket as follows: var server = http.createServer(app); var io = require('socket.io')(server); require(& ...

What is the importance of fulfilling a promise in resolving a response?

I have a promise structured as follows: let promise = new Promise((resolve, reject) => { axios.post("https://httpbin.org/post", params, header) .then(response => { resolve(Object.assign({}, response.data)); // resolve("aaaa"); ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

Unable to change the visibility of blockquotes using jquery

Currently, I am delving into the world of basic JQuery functions. My main focus right now is figuring out how to display the active blockquote while keeping the others closed or closing them. Essentially, creating a toggle effect where only one blockquote ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

jQuery .CSS is not working for positioning the element at the bottom right corner!

I am struggling to create a basic Modal Box that can be minimized to the bottom right corner of the screen. I want to turn it into a plugin, but I'm having trouble getting the simple CSS to cooperate and position itself correctly at the bottom right. ...

Discovering the art of integrating RSS feed with GAE database

Is there any game library that can accomplish this task? I believe jQuery may also be able to achieve this, is that correct? Thank you ...

Bidirectional Data Flow with rxjs in Angular

After adapting an Angular template and component from Angular Material's dashboard schematic, I wanted to manipulate the properties on the "cards" object using events and two-way data binding. Initially, it seemed like two-way data binding was working ...

Ways to implement two functions within a single onclick event

Is it possible to call two functions with onclick event? <input id = "test" onclick="func1()"> Can I add another function as well? How would I go about doing that? ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

Having trouble with CSS values not being applied to dynamically injected HTML div elements in Angular 4?

Link to Codepen My Angular calendar application runs smoothly without any errors. However, I am encountering an issue where the CSS styles are not being applied to the page. When I implemented this separately, everything worked fine. But as soon as I inc ...

Decrease the heaviness of a Glyphicon

How can I make Glyphicons appear lighter in weight? I have utilized the "ok" Glyphicon <span class="glyphicon glyphicon-ok"></span> which currently displays as follows: Is there a method to decrease the weight of the icon in order to create a ...

NextJS will redirect the user back to the previous router they came from following authentication

Hello! I am currently facing a challenge in redirecting a user back to the initial page they clicked on after being authenticated. The issue lies in server-side rendering (SSR) and the lack of access to the window.history object in getServerSideProps. The ...

The Angular Material layouts demonstration is experiencing technical difficulties

I'm attempting to run the Angular Material grid layouts demo titled Flex Percent Values, which can be accessed here. Here are some snippets from my HTML code: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-sc ...

Is there a way to retrieve text content from a modal using JavaScript?

I am using ajax to fetch values from my table. $(data.mesIzinTanimList).each(function (index, element) { if (element.izinTanimiVarmi == 'yok') tr = "<tr class='bg-warning text-warning-50' row='" + element. ...

AngularJS allows users to seamlessly retain any entered form data when redirected, enabling users to pick up right where they left off when returning to the form

I am currently working on a user data collection project that involves filling out multiple forms. Each form has its own dedicated HTML page for personal details, educational details, and more. After entering personal details and clicking next, the data ...