#16 Transforming JSON data into HTML | Fundamentals of NODE JS | A Complete NODE JS Course

procademy
27 Oct 202214:53

Summary

TLDRIn this lecture, the process of converting JSON data into a JavaScript object is demonstrated using Node.js. The instructor reads data from a JSON file, converts it into an array of JavaScript objects, and logs the data. They then explain how to display this data on a webpage by creating an HTML file and looping over the array to dynamically insert product details. The lesson concludes by addressing issues with rendering and properly setting content types to ensure the web page correctly displays the product information.

Takeaways

  • 📥 The lecture demonstrates how to read JSON data and convert it into a JavaScript object using the `JSON.parse` method.
  • 📂 The app reads from a `products.json` file and logs the JavaScript array formed from the JSON objects.
  • 📝 A new HTML file `product_list.html` is created to display products dynamically on the web page.
  • 🔄 Placeholders in the HTML file are used to replace hardcoded values with product data from the `products` array.
  • 🔄 The map function is used in JavaScript to iterate over the `products` array and replace placeholders with the corresponding product properties.
  • 💡 JavaScript's `replace` method is used to dynamically insert product data (like `name`, `model number`, etc.) into the HTML template.
  • ⚙️ The `join` method is employed to combine the individual HTML elements from the products array into a single string.
  • 🖥️ After combining, the content is set as the response for the `/products` route, displaying the product list dynamically.
  • 🔧 A mistake with content type `application/json` is corrected to `text/html` to properly render the HTML on the web page.
  • ✔️ The final result displays a list of products dynamically from the JSON data, rendered via Node.js and JavaScript.

Q & A

  • What method is used to convert JSON data into a JavaScript object in the script?

    -The JSON data is converted into a JavaScript object using the `JSON.parse()` method.

  • How does the app handle displaying products on the web page?

    -The app reads the `products.json` file, converts the JSON data into a JavaScript object, and then loops over the products to display them dynamically in the `product_list.html` file.

  • What function is used to loop through the products array?

    -The `map()` function is used to loop through the `products` array, allowing transformations to be made for each product.

  • How are placeholders in the HTML file replaced with product data?

    -Placeholders in `product_list.html` (e.g., `{{name}}`, `{{model_number}}`) are replaced with product properties (e.g., `prod.name`, `prod.model_number`) using the `replace()` method.

  • What does the `join()` method do in the script?

    -The `join()` method is used to combine the elements of the `productHTMLArray` into a single string, removing any commas between the elements.

  • Why was the initial HTML response not rendered as expected?

    -The initial response was not rendered correctly because the content type was set to `application/json`, which caused the browser to interpret the response as JSON instead of HTML.

  • How was the issue with rendering the HTML response fixed?

    -The issue was fixed by changing the content type from `application/json` to `text/html`, which allowed the browser to render the HTML correctly.

  • What is the purpose of the `productResponseHTML` variable?

    -The `productResponseHTML` variable stores the final HTML content with the product data after replacing the placeholders in the `product_list.html` file.

  • What does the `fs.readFileSync()` method do in this script?

    -The `fs.readFileSync()` method is used to read the content of the `product_list.html` file and store it as a string in the `productListHTML` variable.

  • How does the server respond when a user navigates to the `/products` URL?

    -When the user navigates to the `/products` URL, the server sends an HTML response that contains the list of products with their properties dynamically inserted into the template.

Outlines

00:00

📄 Reading and Parsing JSON Data in Node.js

In this paragraph, the focus is on how to read JSON data from a `products.json` file and convert it into a JavaScript object using the `JSON.parse` method. The `app.js` script reads the file and assigns the parsed JavaScript object to the `products` variable. This object is then logged to the console as a JavaScript array, where each element represents a product. The goal is to display this product list on the webpage when a user navigates to `/products`, instead of showing a simple 'You are in products page' message. The next step involves creating an HTML file named `product_list.html` to render the product details dynamically.

05:00

🖼️ Creating and Displaying the Product List in HTML

This section covers how to create a new HTML file (`product_list.html`) to display products on the webpage. Initially, the products are hardcoded in the HTML file. The script reads the `product_list.html` file into a variable and displays it when the user navigates to `/products`. However, the aim is to loop over the products array and dynamically populate product data (like name, model number, and image) in the HTML placeholders using JavaScript. Placeholders are set using double curly braces (`{{ }}`), which will later be replaced with actual product data from the `products` array using the `map` function in JavaScript.

10:01

🔄 Replacing Placeholders with Dynamic Product Data

Here, the focus shifts to replacing the placeholders in `product_list.html` with actual product data from the JavaScript object. Using the `map` function, the script iterates over the `products` array, replacing placeholders like `{{name}}` and `{{image}}` with corresponding values from the product object. The updated HTML content for each product is stored in a new array, and this array is logged to verify the successful replacement. Each element of the array now contains HTML strings representing individual products, where placeholders have been replaced with real data.

🧩 Combining HTML Strings and Sending as a Response

The paragraph describes how to combine individual HTML strings from the product array into a single HTML string using the `join` method. The `join` method merges the elements of the array without any commas, resulting in a continuous string of HTML content. The combined HTML string is then set as the response for the `/products` page. Additionally, a mistake is corrected when trying to join the product HTML array, and the script is modified to send the correct HTML response to the browser by updating the content type from `application/json` to `text/html`. Once corrected, the server displays the full product list on the webpage.

Mindmap

Keywords

💡JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. In the script, it refers to the format of the data being read and converted into JavaScript objects. The app reads a 'products.json' file and then parses this data to display it on the web page.

💡JavaScript Object

A JavaScript object is a collection of key-value pairs, often used to store structured data. In the video, JSON data is converted into a JavaScript object so that it can be manipulated within the application. Each product in the JSON data is represented as a JavaScript object.

💡products.json

'products.json' is a file that stores product data in JSON format. In the script, this file is read and its content is parsed into JavaScript objects. The video focuses on using this data to dynamically generate product listings on a webpage.

💡FS Module

The FS (File System) module in Node.js is used to interact with the file system. In the video, it's used to read the contents of the 'products.json' file and 'product_list.html'. The 'readFileSync' function from this module is specifically highlighted to read files synchronously.

💡Callback Function

A callback function is a function passed into another function as an argument to be executed later. In the video, a callback function is passed to the 'map' method, which processes each product object in the array and generates HTML for it.

💡Map Method

The 'map' method in JavaScript creates a new array populated with the results of calling a provided function on every element in the original array. In the video, this method is used to loop over the 'products' array and transform each product into HTML format by replacing placeholders with product details.

💡Placeholders

Placeholders are used in the 'product_list.html' file as temporary markers to be replaced with actual product data. For example, placeholders like {{name}} and {{price}} are replaced by the corresponding product properties. This enables dynamic generation of the HTML content.

💡join() Method

The 'join()' method is used to combine the elements of an array into a single string. In the video, after transforming each product into an HTML string, the 'join' method is called to combine the product HTML into a single string for rendering on the page.

💡Content-Type

'Content-Type' is a header in HTTP responses that tells the browser what kind of data is being sent. In the video, the 'Content-Type' header was initially set to 'application/json', causing an issue with rendering HTML. Changing it to 'text/html' fixed the issue and allowed the HTML to be displayed correctly.

💡Node.js

Node.js is a runtime environment that allows JavaScript to be run on the server. In the video, the entire product display functionality is built using Node.js, from reading the JSON data and HTML files to serving the generated HTML content to the user.

Highlights

Introduction to reading JSON data and converting it into a JavaScript object using json.parse method.

Logging JavaScript objects converted from JSON shows the structure of the products in an array format.

Objective is to display product data on the web page when navigating to the root URL /products.

Creation of an HTML template (product_list.html) to display the product list dynamically.

Using the 'fs' module to read the product_list.html file and assign its content to a variable in app.js.

Replacing placeholders in the HTML file with product data from the JSON file dynamically.

Usage of JavaScript map function to loop over the products array and transform data for each iteration.

Placeholders like {{product.name}} and {{product.model}} are dynamically replaced with actual product details.

Ensuring dynamic values like size, camera, price, and color are filled in the product list HTML page.

Replacing the hardcoded product image placeholder in the HTML with the actual image from the JSON data.

Combining transformed HTML from the products array using the array join method to remove commas and form a single HTML string.

The final HTML content is rendered on the products page after replacing the placeholder content with actual product details.

Addressing an issue where the wrong content type (application/json) was being sent instead of text/html, causing HTML not to render correctly.

Fixing the content type to text/html allows the product details to be displayed correctly in the web browser.

The JSON data is successfully transformed into JavaScript objects, and product data is rendered dynamically in the Node.js web application.

Transcripts

play00:00

in the last lecture we learned how to

play00:02

read Json data and how to convert it

play00:04

into a JavaScript object

play00:07

so in the app.js here

play00:09

we are reading this products.json file

play00:12

and then we are converting the Json data

play00:15

which we have read from this

play00:15

products.json file into a JavaScript

play00:18

object using this json.pass method

play00:21

and then we are assigning that

play00:22

JavaScript object to this products

play00:24

variable

play00:25

and when we are logging this products

play00:27

variable here you will notice that a

play00:29

JavaScript array has been logged here

play00:31

and inside that array we have those Json

play00:34

objects as a JavaScript object

play00:37

and each object here represents a

play00:39

product and we want to display these

play00:41

products in the web page whenever the

play00:43

user navigates to root URL slash

play00:45

products currently when the user types

play00:48

root URL slash products in the address

play00:50

bar we are showing this response you are

play00:53

in products page but instead of showing

play00:55

this response we want to show the

play00:56

product list in the web page let's see

play00:59

how we can do that for that the first

play01:01

thing which I am going to do is inside

play01:03

this template folder I'm going to create

play01:04

a new HTML file I will call this product

play01:07

list.html

play01:11

and inside this HTML file I'm going to

play01:13

write some HTML and in order to save

play01:16

some time

play01:17

I have already written that HTML so

play01:19

let's copy it from here

play01:21

let's go to vs code and let's paste it

play01:24

inside this product list.html

play01:27

let's move this Terminal A bit down

play01:31

okay so this is the HTML content for

play01:33

this product list HTML now let's go

play01:36

ahead and let's read this product

play01:37

list.html file from our app.js

play01:40

so again

play01:42

here I am going to create a new variable

play01:45

I will call it product list HTML

play01:48

and again I am going to use this FS

play01:50

module and on that I will call read file

play01:53

sync to this let's pass the path of the

play01:56

file

play01:58

so here I will say root directory so dot

play02:01

slash then we have to go to this

play02:03

template folder and inside that template

play02:05

folder we have product list.html

play02:08

okay let's also specify the encoding

play02:11

which is going to be utf-8 so this

play02:14

product list HTML it is going to store

play02:16

the HTML content of this product list

play02:18

HTML file so basically this HTML content

play02:23

now let me show you how this HTML

play02:25

content will look like in the web page

play02:26

so let's copy this variable here and

play02:30

here when the user types the root URL or

play02:33

the root URL slash home there we want to

play02:36

replace this content with this HTML

play02:38

content which we are storing in this

play02:40

product list HTML variable

play02:42

with this let's save the changes let's

play02:44

stop the server by pressing Ctrl C and

play02:46

let's start the server again

play02:48

and now let's go to the web page

play02:51

and here when I type root URL and when I

play02:54

press enter

play02:55

you will notice that a product detail

play02:57

has been shown here

play02:58

let me zoom out this web page

play03:02

okay so a product list has been

play03:04

displayed here and currently we are hard

play03:07

coding these values so if I go to that

play03:08

HTML file this product list.html file we

play03:12

are hard coding these values

play03:13

but what we actually want is

play03:16

we want to Loop over this products array

play03:19

and for each iteration in the product

play03:21

list.html file we want to use the

play03:24

properties of the product object so for

play03:27

example if I scroll up here we have a

play03:30

product object logged in the terminal so

play03:32

here instead of this hard-coded value I

play03:35

want to use product.name instead of this

play03:37

model number I want to use product dot

play03:39

model number property okay but currently

play03:42

we are hard coding those values

play03:44

so first of all from the fjs let's get

play03:47

back the previous code so in the home

play03:49

page we want to display your in home

play03:51

page

play03:52

and here

play03:54

on this products array I am going to use

play03:57

map function so we can use map function

play03:59

to Loop over an array in JavaScript and

play04:02

for each iteration we can transform the

play04:04

elements of that array so here I am

play04:06

going to use this map function to this

play04:07

map function we need to pass a callback

play04:09

function and this callback function is

play04:11

going to receive the current element

play04:12

from this array for each iteration so I

play04:15

will simply call it prod

play04:18

now I will go back to this product

play04:20

list.html and as I mentioned earlier

play04:23

instead of using these hard-coded values

play04:25

we want to use the properties of the

play04:27

product object which we are going to

play04:29

receive inside this product parameter so

play04:32

here I am going to use some placeholders

play04:34

and for the placeholder again I will use

play04:36

a set of double curly braces inside that

play04:38

I will use percentage and then I will

play04:41

set a name here so here I will say the

play04:43

placeholder is name

play04:45

in the same way let's do the same thing

play04:47

for model name model number and other

play04:49

properties so here I will say model name

play04:55

and actually it should be model number

play04:56

so model no I will say here this is the

play05:00

model name so here I will say model name

play05:03

here I will use the name placeholder so

play05:06

here we want to display the product name

play05:07

in the same way let's also use size

play05:10

placeholder here

play05:12

here let's use the camera placeholder

play05:15

here let's use the price placeholder

play05:18

because here we want to display the

play05:19

price

play05:20

here let's use the color placeholder

play05:24

and then we also want to display the

play05:26

image of the product so to this Source

play05:28

attribute we are going to specify a

play05:30

placeholder and there I will name this

play05:33

placeholder as image

play05:36

and in the fjs for each iteration we are

play05:39

going to replace this placed holder with

play05:42

the properties of that product object

play05:45

so here what I am going to do is inside

play05:46

the body of this callback function let's

play05:48

create a variable let's call it maybe

play05:50

output

play05:52

and to that output let's assign this

play05:54

product list HTML

play05:57

and in this product list HTML we want to

play06:00

replace some placeholders so to this

play06:03

replace method first we need to pass the

play06:04

value which we want to replace let's say

play06:06

we want to replace this placeholder

play06:10

with

play06:12

product image property of that product

play06:15

so we are receiving that product object

play06:16

inside this broad parameter and on that

play06:19

we are going to have this product image

play06:21

property

play06:23

okay

play06:24

so in this output variable we will have

play06:27

the same HTML but in that HTML this

play06:30

image placeholder has been replaced with

play06:32

the value of this product image that

play06:35

means this string value

play06:37

now on that updated HTML which we are

play06:40

storing in this output again we are

play06:42

going to replace something so again I

play06:44

will say output dot replace

play06:46

and now let's say I want to replace this

play06:50

name placeholder

play06:53

with the name of the product so we are

play06:56

storing the name of the product inside

play06:57

this name property so here I will say

play06:59

broad.name

play07:01

and we are going to assign this result

play07:03

back to this output variable itself

play07:06

so now in this output variable

play07:09

this image is replaced with the value of

play07:12

the product image property and this name

play07:14

placeholder is replaced with the name of

play07:17

the product

play07:18

now let's go ahead and let's do the same

play07:20

thing for other placeholders so I will

play07:22

pause this video here and I will replace

play07:24

these placeholders with the property

play07:26

values of that product

play07:28

let's go to app.js and let me do that

play07:46

okay so here I have replaced all the

play07:49

placeholders which we have specified

play07:50

inside this product list.html with the

play07:53

properties of that product

play07:55

finally let's go ahead and let's return

play07:57

this output from here

play07:59

and once the map method has finished

play08:02

iterating over this products array it is

play08:04

going to return a new array with the

play08:06

transform data

play08:07

let's go ahead and let's store that new

play08:09

transform data into a variable and let's

play08:12

call it product HTML re

play08:16

and now let me go ahead and let me log

play08:18

this product HTML array so when the user

play08:21

will make a request to this root URL

play08:23

slash products first we are sending this

play08:25

text response and then let's also go

play08:27

ahead and log this products HTML array

play08:29

just to check what it contains

play08:32

let's save the changes here let's stop

play08:34

the server by pressing Ctrl C and let's

play08:36

restart the server

play08:38

and let's go ahead and let's make a

play08:40

request to this products page

play08:42

so in the response we see you are in

play08:44

products page let's go to vs code and

play08:47

here you will notice that some string

play08:49

has been logged here let me move this

play08:51

terminal a bit up

play08:53

okay so basically here you will see that

play08:56

we have an array

play08:58

so here you can see we have an array

play09:00

because it starts with this opening

play09:02

square bracket and in that this HTML is

play09:05

the first element

play09:07

then we have a comma

play09:09

and then this HTML is the second element

play09:12

of that array and if you notice in these

play09:15

htmls these values are replaced by the

play09:18

actual value which we have read from the

play09:20

product.json file now these values are

play09:22

not hard coded here the placeholders

play09:25

have been replaced with the property

play09:27

values of that particular product object

play09:31

okay then again we have a comma and then

play09:33

we have the third element so each of

play09:36

these elements of this array are

play09:37

actually htmls we have htmls which are

play09:40

quoted so basically we have strings

play09:42

and in that string we have some HTML

play09:44

content

play09:46

now what we want is we want to combine

play09:49

these elements of this array which we

play09:52

are receiving here which this

play09:56

product HTML array is returning we want

play09:58

to join each elements of this array into

play10:01

a single value and to join elements of

play10:04

an array into a single value on that

play10:06

array we can use join method

play10:09

and to this join method we need to pass

play10:12

the separator so here the elements are

play10:14

separated by a comma so here we will

play10:16

pass comma as the separator or delimiter

play10:19

you can say and based on this this join

play10:22

method is going to join all the elements

play10:24

of this products HTML array so basically

play10:26

it is going to remove this comma from

play10:28

the array and it is going to join all

play10:30

the elements

play10:31

and it is going to return us a single

play10:33

value in this case it is going to return

play10:35

as a single string value

play10:37

and to check that save the changes let

play10:40

me clear the console here

play10:45

and let's run this app.js once more

play10:48

and let's go ahead and let's again make

play10:50

a request to this products page

play10:52

so we still see this response but now if

play10:54

I go to the vs code here you will notice

play10:57

that now instead of logging an array we

play11:00

are seeing some HTML content so

play11:02

basically all the elements of that array

play11:04

has been combined into a single HTML

play11:06

content we don't see any commas here

play11:09

and we want to send this HTML here as a

play11:12

response for the products page

play11:15

so let's go ahead and let's do that

play11:17

so first of all what I'm going to do is

play11:19

let me first remove this console.log

play11:21

statement

play11:22

and before sending the response

play11:26

first what I'm going to do is I'm going

play11:28

to take this HTML variable here

play11:34

and here in this HTML variable basically

play11:37

this HTML variable is storing this

play11:39

index.html

play11:40

in this index.html we have this

play11:42

placeholder called content so I want to

play11:45

replace this content for that on this

play11:47

HTML I can use this replace function and

play11:50

there I want to replace this content

play11:53

which we have inside this index.html as

play11:55

a placeholder with the HTML content

play11:58

which we are storing inside this

play12:01

product list HTML so here I will pass

play12:06

product list HTML dot join because here

play12:09

we want to join all the elements of this

play12:11

product list HTML array into a single

play12:13

string and we want to join it by comma

play12:16

and here let's go ahead and let's do the

play12:19

result in a variable let's call it maybe

play12:21

product response HTML

play12:25

and let's go ahead and let's return this

play12:28

HTML as a response

play12:30

so here instead of returning this text

play12:32

response now we are returning the HTML

play12:35

response

play12:37

let's save the changes here let's stop

play12:39

the server by pressing Ctrl C

play12:42

and let's restart this server by running

play12:44

this node.js app

play12:46

let's go to the web page

play12:49

and Let me refresh the page

play12:51

and here we don't see any content let's

play12:53

go back to vs code

play12:57

and it says product list HTML dot join

play12:59

is not a function

play13:01

that's because

play13:04

here we need to use this product HTML

play13:07

array

play13:08

because this is an array and we can use

play13:10

the join method on an array only

play13:13

so here it should be

play13:15

product HTML array with this let's save

play13:17

the changes

play13:19

and let's go ahead and let's run this

play13:22

fjs again let's go to the web page and

play13:25

let's again make the request to this

play13:26

products page

play13:28

and here we do get the HTML response but

play13:32

this HTML response is not rendered as we

play13:35

expected and that's because

play13:38

here if you notice we are setting the

play13:40

content type as application slash Json

play13:43

that means here we are telling the

play13:45

browser that we are sending a Json data

play13:48

and that's why the HTML response which

play13:51

we are sending from here that is treated

play13:52

as a Json data and not as an HTML

play13:55

so here all we have to do is we have to

play13:58

change this content type to text HTML

play14:01

with this let's save the changes

play14:04

let's stop the server and let's restart

play14:06

the server let's go to the web page

play14:10

and now let's refresh the page

play14:15

and now you will notice that all the

play14:17

products are displayed here in this web

play14:18

page

play14:23

okay

play14:28

so here

play14:29

we transform this Json data into a

play14:33

JavaScript object and then we are making

play14:35

use of that JavaScript object to display

play14:38

it in the web page from our node.js

play14:40

application

play14:42

this is all from this lecture if you

play14:44

have any questions from this lecture

play14:45

then feel free to ask it thank you for

play14:47

listening and have a great day

Rate This

5.0 / 5 (0 votes)

相关标签
JSONJavaScriptNode.jsWeb DevelopmentProduct DisplayHTMLTemplatesData TransformationFS ModuleDynamic Content
您是否需要英文摘要?