0

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?

3
  • w3schools.com/json/json_syntax.asp Commented Mar 14, 2016 at 2:16
  • Thanks @Gary, I was able to access the value of the variables. I have one question, what does 'window.videos' do and why has it been used? Commented Mar 14, 2016 at 2:34
  • Not sure of what the server or data wants to be shown or referred to as but var data = [jsonarray] should also work. Commented Mar 14, 2016 at 3:15

1 Answer 1

1

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);
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.