Create list from json javascript

Welcome to a quick tutorial on how to create HTML lists from JSON data in Javascript. Want to dynamically generate a list from JSON data?

To create an HTML list from JSON data:

  1. Parse the JSON data into an array first (assuming it is a flat array) var data = JSON.parse(DATA);
  2. Loop through the array and create the HTML list.
    • var list = document.createElement("ul");
    • for (let i of data) { var item = document.createElement("li"); list.appendChild(item); }
  3. Lastly, append the list to where you want document.getElementById(ID).appendChild(list);

That should cover the basics, but read on for more examples!

I have included a zip file with all the source code at the start of this tutorial, so you dont have to copy-paste everything Or if you just want to dive straight in.

REAL QUICK SLIDES

Firstly, here is the download link to the example code as promised.

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world If you need answers urgently, please check out my list of websites to get help with programming.

HTML LIST FROM JSON DATA

All right, let us now get into the examples of how to create an HTML list from JSON data.

1) CREATE ELEMENT

This is the full version of the snippet in the introduction, and it should be pretty self-explanatory:

  • We use JSON.parse() to turn the JSON string back into an array.
  • Create the HTML list using document.createElement("ol").
  • Then loop through the array, append the list items for (let i of data) { ... document.createElement("li") ... }.
  • Lastly, add the list to where it is required document.getElementById(TARGET).appendChild(list).

2) MANUAL HTML STRING

Dont like the object-oriented way of using createElement() and appendChild()? This is an alternative, where we create an HTML string instead.

3) NESTED OBJECTS & LISTS

Lastly, what if we have a nested object? Keep calm and look carefully, we are pretty much doing the same. Parse the JSON data into an object, then loop through the nested object to create a nested list.

INFOGRAPHIC CHEAT SHEET

HTML List From JSON Data (Click To Enlarge)

LINKS & REFERENCES

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Video liên quan

Chủ đề