ArticleZip > Json Stringify Output To Div In Pretty Print Way

Json Stringify Output To Div In Pretty Print Way

When you're working with JSON in your web development projects, being able to display the output in a user-friendly way can make a big difference in how easily you can debug and understand your code. Fortunately, with a little bit of JavaScript, you can quickly and easily stringify JSON output and display it in a pretty print way within an HTML div element.

To achieve this, we will first need to understand how to stringify a JavaScript object using the `JSON.stringify()` method. This method converts a JavaScript value, usually an object or array, into a JSON string.

Here's a basic example to get us started:

Javascript

const data = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(data, null, 2);

In this example, we have an object called `data` with some sample information. By calling `JSON.stringify()` on this object, we convert it into a JSON string and use `null, 2` as parameters to add indentation for a prettier output.

Next, let's see how we can display this JSON string within an HTML `div` element. We will write a function that takes the JSON string and injects it into the specified `div`.

Javascript

function displayJsonPretty(inputJson, targetDivId) {
  const targetDiv = document.getElementById(targetDivId);
  if (!targetDiv) {
    console.error(`Div element with Id '${targetDivId}' not found.`);
    return;
  }

  try {
    const parsedJson = JSON.parse(inputJson);
    targetDiv.innerHTML = JSON.stringify(parsedJson, null, 2);
  } catch (error) {
    console.error('Invalid JSON format:', error);
  }
}

const jsonString = '{"name":"John","age":30,"city":"New York"}';
const targetDivId = 'outputDiv';
displayJsonPretty(jsonString, targetDivId);

In this function `displayJsonPretty()`, we first locate the HTML `div` element with the specified `targetDivId`. If the element is not found, an error message is logged, and the function stops execution.

We then attempt to parse the input JSON string using `JSON.parse()`. If the JSON is valid, we stringify it with proper indentation and assign it to the `innerHTML` property of the target `div`. In case of invalid JSON, we catch the error and log a message.

To implement this in your project, ensure the JSON string and target `div` ID are appropriately set and call `displayJsonPretty()` with the provided parameters.

Displaying JSON output in a pretty print way within an HTML `div` can greatly enhance the readability of data during development and debugging. With the simple approach outlined above, you can easily integrate this functionality into your web projects.