Stay Tuned!

Subscribe to our newsletter to get our newest articles instantly!

Javascript

How to display JSON data in Javascript

JavaScript’s versatility allows effortless manipulation and display of JSON (JavaScript Object Notation) data, a widely used format for data interchange. Displaying JSON data involves accessing its properties and presenting it in a readable format within web applications. Let’s explore various methods to effectively display JSON data in JavaScript.

Understanding JSON Data

JSON represents structured data in key-value pairs and arrays, commonly used for API responses, configuration files, and data storage.

Displaying JSON Data in JavaScript

1. Accessing JSON Data

Consider a JSON object:

const jsonData = {
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com"
};

Accessing and displaying data:

console.log(jsonData.name); // Output: 'John Doe'
console.log(jsonData.age); // Output: 30
console.log(jsonData.email); // Output: 'john@example.com'

2. Displaying JSON in the Console

For a quick view in the browser console:

console.log(JSON.stringify(jsonData, null, 2));

3. Rendering JSON in HTML

Displaying JSON data in an HTML element:

<div id="jsonDisplay"></div>
const jsonDisplay = document.getElementById('jsonDisplay');
jsonDisplay.textContent = JSON.stringify(jsonData, null, 2);

4. Looping through JSON Arrays

For JSON arrays:

const jsonArray = [
  { "id": 1, "name": "Apple" },
  { "id": 2, "name": "Banana" },
  { "id": 3, "name": "Orange" }
];

// Loop through the array and display data
jsonArray.forEach(item => {
  console.log(item.name);
});

Formatting and Enhancements

  • Prettifying JSON: Use JSON.stringify() with formatting parameters (null, 2) for better readability.
  • Rendering in HTML Elements: Use <pre> tags for preserving formatting or use libraries like highlight.js for syntax highlighting.

Conclusion

JavaScript provides straightforward ways to access and display JSON data. By leveraging JavaScript’s native methods, developers can seamlessly render JSON objects and arrays within web applications. Whether it’s logging data in the console, displaying in HTML elements, or looping through arrays, these methods offer flexibility in presenting JSON data.

Happy Coding !

Avatar

Carolina

About Author

Leave a comment

Your email address will not be published. Required fields are marked *

You may also like

Javascript Tech

How to change Lowercase to Uppercase in Javascript

There are many variations of passages of Lorem Ipsum available but the majority have suffered alteration in that some injected
Javascript

How to refresh page after update in JavaScript

In JavaScript, refreshing a page after an update is a common requirement to ensure users view the latest content or
en_USEnglish