Display the contents of a nested JavaScript object

I need help creating a custom JavaScript function that will transform an object into a nicely formatted JSON-style string for debugging purposes. My current approach of iterating over object properties does not handle nested objects properly, resulting in [object Object] being displayed. How can I write a short and simple solution to convert nested objects into multiline strings that can be easily printed to the console?

Unfortunately, the JSON.stringify function is not available within my iAd Producer environment. Therefore, I am seeking a compact function that I can simply copy and paste.

For instance:

stringify({ data: { hello: 'world', with: { nested: 'objects' } })

The expected output should be:


{
  "data": {
    "hello": "world",
    "with": {
      "nested": "objects"
    }
  }
}

Answer №1

If the JSON methods are not readily available to you, an alternative option is to integrate a library that will provide them:

https://github.com/douglascrockford/JSON-js/blob/master/json2.js

By doing this, you can utilize JSON.stringify(myobj, null, 2) to generate a two space indented JSON output.

One of the key benefits of using such a library is the assurance of thorough testing and consideration for various edge cases.

Answer №2

If you are in need of a quick debugging solution, one option is to create a basic recursive function that converts the object's contents into a string. Keep in mind that this method may not handle certain data types like Date objects (which will be displayed as [object Date]).

For a more robust and reliable approach that covers all scenarios and ensures valid JSON output suitable for production environments, consider utilizing libraries such as json2.

function stringify(object, indentation) {
  if (typeof indentation === 'undefined') {
    indentation = 0;
  }

  var items = [];

  for (var key in object) {
    if (object.hasOwnProperty(key)) {
      var value;

      switch (typeof object[key]) {
        case 'object':
          var type = Object.prototype.toString.call(object[key]);

          switch (type) {
            case '[object Null]':
              value = 'null';
              break;

            case '[object Array]':
            case '[object Object]':
              value = stringify(object[key], indentation + 2);
              break;

            default:
              value = type;
          }
          break;

        case 'string':
          value = '"' + object[key] + '"'
          break;

        default:
          value = object[key];
      }

      items.push(Array(indentation + 3).join(' ') + '"' + key + '": ' + value);
    }
  }

  return '{\n'
         + items.join(',\n') + '\n'
         + Array(indentation + 1).join(' ') + '}';
}

-

// Example:
console.log(stringify({ data: { hello: 'world', with: { nested: 'objects' } } }));

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

Node.js/Hapijs - Verify every property and value in JSON object payload without explicitly naming the properties

One of the challenges I'm facing with my API is handling POST-sent payload input that needs to be passed on to another application for processing. The input is always in JSON format, and the values must strictly be numeric. With hundreds of different ...

The Cordova Mobile Package fails to display the Frontend

As I work on developing a web application, I am utilizing Cordova to package it into a mobile app. While the build process is successful, the mobile app is not displaying the actual frontend of my application. I have conducted tests on the Cordova build, ...

JSONP callback function enables cross-domain communication by allowing a

After delving into the world of JSONP callback functions, I decided to familiarize myself with the concept by researching articles. To further understand JSONP, I uploaded a JSON file onto the server - json file Below is the JavaScript code I used to fet ...

How can I access the value of one method within the same class and use it in another method in Ionic?

I encountered an error while trying to utilize data from my API call in IONIC's home.ts file for the google map method also located in home.ts. Unfortunately, this resulted in a null or undefined error. Is there a way to effectively use data from one ...

Total of the Selected Rows

In my webpage, I have a table structured like this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

What steps do you take to establish a relay connection for pagination in an ORM framework?

After thorough research of Relay's documentation, I have yet to find a clear explanation on how to establish a Relay connection with an ORM. The examples provided mainly utilize the connectionFromArray method, which works well for data stored in memor ...

React: Issue encountered when updating props from parent component (Error executing removeChild operation)

Currently, I am utilizing react along with AJAX to retrieve data for a list. However, every time componentWillReceiveProps(nextProps) is triggered after the initial setup, an error occurs. This error typically arises when the URL for the AJAX call has chan ...

Addressing the font file path in an SCSS file while utilizing webpack

I'm struggling to get my font paths resolved while using webpack with my asp.net mvc core project. I've successfully bundled js files, but the font paths are causing me trouble. Here is an excerpt from my scss file: $font-path: '../fonts&a ...

What are the drawbacks of adding a .js file with Express.js code to an HTML file?

Instead of an unresolved issue, I have a technical inquiry that I believe is worth exploring. Being a novice web developer, I tried to pass a variable from a .js file to an .html file in order to display it on the screen. My intention was to do this using ...

Positioning with Bootstrap CSS libraries

The text next to the logo in the navbar isn't aligning properly (refer to this link for the page -> ). Furthermore, the logo isn't positioning correctly either, and this issue is present in all the navbar codes. I'm utilizing CSS bootstr ...

AngularJS: Changes to the model do not automatically reflect in the view

Currently, I am developing a web-based Twitter client using Angular.js, Node.js, and Socket.io. Tweets are pushed to the client via Socket.io, where a service listens for new tweets. When a new tweet arrives, the service triggers an event using $broadcast. ...

What are some ways to ensure that my gltf loader in three.js operates synchronously?

I have a question regarding my code. I'm currently working on making the loadCone() function synchronous using async/await, but I'm facing some issues with it. import * as THREE from "three"; import { GLTFLoader } from "three/exam ...

When attempting to execute the npm install command within Visual Studio Code, an error message is being displayed

[ Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Explore the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\sahib\Downloads\generative-art-node-main (1)> npm install npm ERR! code ENO ...

The div element on the HTML page is not displaying all of its content

I've created the following code snippet on JSFiddle. https://jsfiddle.net/msridhar/1zvhmpjq/11/ HTML file: <body> <div id="headerDiv"> <img id="headerImg" src="" width="280" height="125" alt="DummyLogo"/> <pre id ...

Obtaining a Slug in the Server-Side Layout of a Next.js Component

I am facing an issue with passing a slug to a server-side function in my Next.js layout component. The problem arises when the slug is returning as undefined, and I am struggling to correctly access and utilize the slug on the server side within the layout ...

Prompt triggered within AJAX request

I am facing an issue with my ajax call in which I am trying to invoke a php function containing an alert. However, the alert is not getting triggered and instead it returns me the JavaScript code (visible inside the console). How can I successfully use an ...

The WebDriver encountered an error while trying to click on an element

When using Selenium WebDriver, I am facing an issue with selecting an item from a drop-down list. The element I want to click on is labeled as "game club". Despite attempting to select different elements, I keep encountering an error stating that none of ...

Unable to display search results with AJAX in Select2

I'm struggling with getting the desired outcomes to display in Select2 when using AJAX. Below is my code: $(document).ready(function() { $("#producto").select2({ placeholder: 'Select a product', formatResult: productForm ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...