innowqhy
innowqhy

Reputation: 53

Access data from an external Javascript file

I have data that's stored in an external Javascript file.

It looks like this,

window.videos = [{
    "name": "Sample data",
    "duration": 154,
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras hendrerit tempor velit.",
    "tags": ["modern-society",
    "ABC"]
},
{
    "name": "Sample data",
    "duration": 2659,
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras hendrerit tempor velit.",
    "category": "Senior->English",
    "tags": ["China"]
}];

What is it? Is it JSON or an object?

I need access and retrieve the name and description from this file and display it in my HTML, how do I do it?

Upvotes: 0

Views: 75

Answers (1)

JoshWillik
JoshWillik

Reputation: 2645

The code you have posted is creating a javascript object, but if you remove the window.videos =, you have a valid JSON document too. (The two are very similar)

Let's assume you leave the code as-is, and put it in a file called video-data.js.

Once this script ran, window.videos would contain the video data you specified.

If you wanted to take this data out of javascript and display it in HTML, could loop through the array and construct some elements on the page.

window.videos = [{
  "name": "Sample data",
  "duration": 154,
  "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras hendrerit tempor velit.",
  "tags": ["modern-society",
    "ABC"
  ]
}, {
  "name": "Sample data",
  "duration": 2659,
  "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras hendrerit tempor velit.",
  "category": "Senior->English",
  "tags": ["China"]
}];

videos.forEach(function(video) {
  var videoElement = document.createElement('p');
  videoElement.innerHTML = '<strong>' + video.name + '</strong>: <i>' + video.description + '</i>';
  document.body.appendChild(videoElement);
});

Upvotes: 1

Related Questions