Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
javascript

How to convert JSON to HTML

Shahpar Khan

JSON

JSONJavaScript Object Notation is a lightweight, text-based data-interchange format. JSON is based on two basic data structures ( key-value pairs and ordered lists ) and is language-independent. In JSON, data can only be in text form while it is exchanged between a browser and a server. Any JavaScript object can be converted into JSON text.

HTML

HTMLHypertext Markup Language is a language used to design and display web pages. HTML is a formatting language that focuses mainly on its tags and attributes to markup webpages. HTML cannot be referred to as a programming language as it does not contain any conditional statements or dynamic structure.

Methods to convert JSON to HTML

  1. Use an online convertor
  2. Use JSON functions

How to use an online convertor

Using an online converter to convert JSON to HTML is a bit tedious and it might not be resorted to dynamic conversion over a website. However, this tool will come in handy if you want to parse one JSON file for reasons not concerning a particular website. Here is a link to an online converter called ConvertJSON. It looks something like this:

ConvertJSON is pretty straightforward. There are three ways you can give your input:

  1. A JSON file
  2. A URL
  3. Raw JSON text

After giving input, you will receive an HTML text that will convert your JSON into an HTML table. You can copy that and use it!

How to use JSON functions

JSON functions are a more useable method and can be easily incorporated into a web application. The key function that enables us to convert JSON to HTML at runtime is JSON.parse(). The JSON.parse() method takes textual JSON data and converts it to a JavaScript object. You can then easily use this object to display data in HTML. Let’s look at an example:

JSON to HTML

Here we have an object with three attributes:

var my_obj = {name: "Erik", age: 17, school: "Edpresso High"};

In the code above, we first created an object and then converted it to JSON using JSON.stringify(). This is a good way to mimic the conversion because the data is received in textual form over the network:

var my_json = JSON.stringify(my_obj);

We then pass this text to the JSON.parse() function and it converts it into a JavaScript object:

var my_json = JSON.stringify(my_obj);
var parsed_obj = JSON.parse(my_json);

Finally, we use the object to render the HTML tag:

json_to_html_tag.innerHTML =  "Converting JSON to HTML <br><br>" + 
                                "Name: " + parsed_obj.name + 
                                "<br>Age: " + parsed_obj.age +
                                "<br>School: " + parsed_obj.school;

RELATED TAGS

html
javascript

CONTRIBUTOR

Shahpar Khan
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring