The JSON.stringify function encounters difficulties when trying to format an object into

Why does JSON.stringify refuse to format objects and keep everything on a single line?

<!DOCTYPE html>
<html>
  <head>  
    <script>

var obj = {
 "a" : "1547645674576457645",
 "b" : "2790780987908790879087908790879087098",
 "c" : "38907908709879087",
 "d" : "A very long sentance or text1",
 "e" : "A very long sentance or text2",
 "f" : "A very long sentance or text3"

};

// pretty format trick
var myj=JSON.stringify(obj, null, 4);
//var myj=JSON.stringify(obj);
document.write(myj);

</script>

  </head> 
  <body>
</body>
</html>​

Answer №1

JSON.stringify(obj, null, 4) allows you to format the JSON data with indentation.

After formatting it, you can output the result using document.write().

document.write(myj);

However, when presenting JSON as HTML, spaces and new lines may collapse by default, losing the formatting.

To preserve the formatting, wrap the JSON in a <pre> element and consider using document.createTextNode / appendChild instead of document.write to avoid any unintended side effects from special characters.

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

React variable should remain consistent and not change unnecessarily

I've been struggling with an issue for about 3 hours now, and I just can't seem to figure it out. Let me walk you through the problem with the code snippet below: import {useEffect} from 'react' function shuffle(tab) { console.table ...

Improving an HTML list with JavaScript

My current project involves a JavaScript game similar to Scrabble. I want users to be able to create new words in the game, and have those words added to a list that is displayed on the page within a div element. However, I'm struggling to understand ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Tips for passing an array to a different function using Jquery

I need to pass an array to another function <div id="test"></div> <div id="test2"></div> <input type="button" value="chk" id="go" /> <script> $(function() { var c = 1; var i = 5; var dat ...

Grouping geoJSON data on Mapbox / Leaflet

I am currently in the process of setting up a clustered map on mapbox, similar to the example shown here: At the moment, my point data is being extracted from MYSQL and then converted into GeoJson using GeoPHP. You can view the current map setup here. I ...

Looking to confirm client-side text in NodeJS?

As I work on constructing a to-do list, one challenge I am encountering is confirming that the correct task has been checked off. While considering using unique IDs for each individual task may seem like a solution, there is still the risk of users manipul ...

Help needed with using Regex to restrict the number of alphabetical characters allowed

Struggling with configuring RegEx's. Seeking guidance to create a RegEx with the following criteria: Only allow numbers (0-9) Allow a period (.), negative sign (-), plus sign (+), dollar sign ($), and comma (,) Do not permit any alphabetic characte ...

Troubleshooting Next.js 14.1 Pre-rendering Issue: A Step-by-Step Guide

I just updated my Next.js from version 14.01 to 14.1 and encountered an error during the build process of my application. How can I resolve this issue? The error message reads as follows: Error occurred while prerendering page "/collections". For more inf ...

How can Tweepy be utilized to extract the integer count and incorporate it?

Hope all is well with everyone here. My apologies if this question has been addressed previously, but I am currently working on the following task. cursor = tweepy.Cursor( api.search_tweets, q = '"Hello"', lang = 'en&ap ...

Tips for troubleshooting Grunt in PHPStorm (or WebStorm)

Looking for tips on debugging grunt, such as using an event listener function, in PHP Storm. Does anyone have any ideas? I know that PHP Storm has Node.js support, but I'm not sure how to configure debug settings for debugging a grunt task. For examp ...

Analyzing Compatibility and Ensuring Security

I recently started using Parse and have been exploring the documentation and answered questions. However, I still have a couple of inquiries on my mind. Firstly, I discovered that the Javascript SDK does not function on IE9 and IE8 without an SSL certific ...

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

How should the value of 'true' be formatted in JSON?

While some JSON parsers may consider it invalid, both PHP and Javascript treat a simple true response as valid JSON: true In PHP, the following code snippets demonstrate how "true" is considered valid JSON: PHP- echo json_encode( true ); // outputs: tr ...

Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body. The structure of my database is as follows: "cart": { "items": { "0": {info here}, "1": {info ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Pass data from PHP to JS after triggering AJAX communication

*Updated with full code example, after receiving feedback I decided to share a sample of the code that is giving me trouble. Essentially, I am trying to achieve the functionality where clicking on a link in the HTML will submit a form to called.php and dis ...

Scrolling does not function properly on Android devices when utilizing skrollr.js in conjunction with multiple div elements containing the id "skrollr-body."

Having trouble with the scroll functionality in my skrollr.js animations. Everything works fine on desktop, but when I checked the rendered HTML in the browser console, I noticed that there are two divs with the same id "skrollr-body". One is empty and the ...

Obtain similar words and related terms

My goal is to extract information from www.thesaurus.com, specifically related to synonyms and antonyms of a word. In this case, let's consider the word angry. I am interested in the words displayed in these images (focusing only on the first 2 blocks ...

Is there a way to resolve the scrolling problem on Google Maps?

When using the Google Maps V3 API, an issue arises where zooming out on the map using the scrollbar also causes the page to scroll along with it. This can be quite frustrating and so far I have not been able to find a way to disable this scrolling behavi ...