Transforming a JavaScript object into a nicely formatted string

How can I format an object to be displayed as a structured string like with <pre>, without using jQuery?

This is how my object currently appears when using console.log.

Object
   title: "Another sting"
   type: "tree"
   options: Object
      paging: "20"
      structuretype: "1"
   columns: Object
      ...
   description: "This is a string"
   ...

What's the best way to convert it to a nicely formatted string?

My solution attempt:

I attempted using stringify() to generate a JSON structure. I could create my own parser, but I'm wondering if there are existing implementations available.

Answer №1

JSON.stringify function includes an argument for formatting:

JSON.stringify(value[, replacer [, space]])

The space parameter can be utilized to adjust spacing within the resulting string. If it is a number, each successive level in the string representation will be indented by that number of spaces (up to 10). If it is a string, each successive level will be indented by that specific string (or the first ten characters of it).

By using a tab character, you can achieve a standard pretty-print look.

Visit this link for more information.

Does this level of formatting meet your requirements? For example, you can try:

 JSON.stringify( object, null, 2 );

If not, you may want to explore http://code.google.com/p/google-code-prettify/, a standalone JSON to HTML prettifying tool. It is widely used by platforms like Stack Overflow and Google Code.

Answer №2

Here is a custom function that I wrote and thought I'd share:

generateTabs: function(numTabs) {
         var tabString = '';
         for(var i = 0; i < numTabs; i++) {
            tabString += '**';
         }
         return tabString; 
      }

convertObjToString: function(obj, tabLevel) {
         var self = this;
         var outputString = '';
         tabLevel = tabLevel || 0;

         for(var element in obj) {
            if(typeof obj[element] === 'object' || Object.prototype.toString.call( obj[element] ) === '[object Array]') 
            {
               outputString += self.generateTabs(tabLevel) + element + "<br />";
               outputString += self.convertObjToString( obj[element], tabLevel+1);
            } 
            else 
            {
               outputString += self.generateTabs(tabLevel) + element + " = " + obj[element] + "<br />";
            }
         }
         return outputString;
      }

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

Express.js fails to recognize the HTML meta viewport tag

I am currently facing an issue with the code I have written. I am testing it on Chrome 67 on Android 8.1 from two different sites. One site, served by Apache, has the following URL: The other site, served by express.js, has the following URL: Both sites ...

Improve the organization of my JavaScript code

This code snippet is specifically designed for a shoe website, where it automatically adds the shoe in the desired size to your cart as soon as the page loads. The "skuAndSize" variable represents the shoe size used by the website. In this case, a selecte ...

Having difficulty displaying nested arrays in AngularJS

Understanding JSON Data in AngularJS As I delve into the world of AngularJS, I've encountered a minor roadblock when it comes to fetching JSON data. <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/boots ...

How to Implement Drupal.behaviors for Specific Pages?

Currently, I have a module that showcases an alert to users within a block. For those interested, you can find my code on GitHub here: https://github.com/kevinquillen/User-Alerts If you would like more information about the module and its functionality, ...

Activate a Bootstrap tab using turbolinks dynamically

After loading the page, I am attempting to open a Bootstrap 4 tab. It works when I refresh the page, but if I navigate within the site, it gives me a query selector empty error. This code is a port of the solution mentioned in this tutorial, as I am using ...

"Unpredictable test failures plaguing my Node.js application with jest and supertest

Recently, I've been working on developing a REST API that accepts a movie title in a POST request to the /movies route. The API then fetches information about that movie from an external API and stores it in a database. Additionally, when you make a P ...

What is the best way to use Promise.all() to delay the return of an array that is currently being constructed within the function?

In the following code block, I am trying to set an array as the value for a local variable by calling a function that returns an array. The issue arises because the Promises in the second function are not resolved until after the array has been returned to ...

Utilize the HTML canvas to sketch on an image that has been inserted

I have a HTML canvas element within my Ionic application. <canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas> Within this canvas, I am loading an image. Below is the code snippet from the con ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Retrieve the function-level variable within the while loop's else statement

Struggling with node.js, I find myself facing the challenge of accessing a variable declared at the start of a function from an else statement nested within a do while loop: function myFunction(){ var limit = 2000; var count; var total; va ...

PHP code to generate a JSON file with a multi-dimensional array: "

Within my web application, I am utilizing JSON. It is necessary for me to generate the following JSON file format using PHP. { "title": "A fantastic article", "clicks": 4000, "children": null, "published": true, "comments": [ ...

http-proxy-middleware - serving static content

I am currently working on integrating my static landing page with an express.js app (using react.js for the single page application). For my landing page, I have set up a proxy using http-proxy-middleware. Here is what my server.js file for the static pag ...

What is the data type of the JSON file content in the R programming language?

I'm working with a JSON file saved on my local machine. I am curious about the data structure of the output. Will it be a dictionary, list, or string? Here is the code snippet from my Rstudio: install.packages("rjson") library("rjson") output <- f ...

Transforming data from PHP JSON format into HTML output

Struggling to convert JSON data into HTML format? Having trouble maintaining the correct order of child elements in your structure? Here's a solution: Take a look at this example JSON: { "tag": "html", "children": [ { "ta ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Iterating through elements to set the width of a container

I am currently working on a function that dynamically adjusts the width of an element using JavaScript. Here is my JavaScript code: <script> $('.progress-fill span').each(function(){ var percent = $(this).html(); if(per ...

How to hide functions in Angular source code

Here's a common query. Typically, the code we develop in Angular gets compiled into a bundle file that is then sent to the browser, correct? The JavaScript code we write can be easily seen as is in the bundle file when viewing the source. How can we ...

A guide on sorting JSON data with Javascript/jquery

I have a set of JSON data: {"X1":"3","X2":"34","Y1":"23","Y2":"23","Z1":"234","Z2":"43",...} My goal is to rearrange and group this data as follows: var newDataJson1 = { "X":{"X1":"3","X2":34}, "Y":{"Y1":"23","Y2":"23"}, ... } ALSO, I want to stru ...

Having trouble with the Tap to copy discount code function not working in the Shopify cart drawer?

Our goal is to implement tap to copy functionality for code snippets on our Shopify website. It works seamlessly on the product detail page, but in the cart drawer, it only functions properly after the second page load. https://i.sstatic.net/xzMVY.png ...

Retrieve JSON response from a RESTful Java web service

Whenever I try to access the URL http://localhost:8081/projectName/pathh/param, it is supposed to display the JSON Object that was created "Employee": [{ "id": "param" }] This piece of code is written in Java and I am using Eclipse with Tomcat Serve ...