Retrieving the attributes of a JSON object based on their names

I'm currently working on storing video information using JSON. I've managed to successfully read the JSON file, but I'm facing some challenges when trying to access the properties of the object. Specifically, I'm struggling with accessing the "fastvideos" array as obj.fastvideos[x] is returning undefined even though the array is loaded as an object.

Could this issue be related to my JSON structure, or am I making a mistake in how I'm attempting to access the object?

JSON

{
"fastvideos": [{
    "video-title": "sampletitle",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }, {
    "video-title": "sampletitle2",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc-2",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }]
}

JS

var obj = $.getJSON("videolist.json", function(json){
console.log(json);
});

document.getElementById("demo").innerHTML =
obj.fastvideos[1].video-title + ": URL =  " + obj.fastvideos[1].video-url;

Answer №1

To access the properties video-title and video-url, you must use bracket notation due to the hyphen character.

Additionally, when calling getJSON, it does not directly return the JavaScript object but instead provides a reference to a jqXHR object. In this scenario, you can avoid using that object since there is a function listening for a successful callback, which will contain the parsed JavaScript object as a parameter.

$.getJSON("videolist.json", function(obj){
    document.getElementById("demo").innerHTML =
    obj.fastvideos[1]["video-title"] + ": URL =  " + obj.fastvideos[1]["video-url"];
});

Here's how you can iterate through the videos:

var obj = 
{
"fastvideos": [{
    "video-title": "sampletitle",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }, {
    "video-title": "sampletitle2",
    "video-tags": "tag1, tag2, tag3",
    "video-desc": "sample-desc-2",
    "video-url": "https://www.youtube.com/watch?v=<redacted>"
    }]
};

for (var i = 0; i < obj.fastvideos.length; i++) {
    var video = obj.fastvideos[i];
    var title = video["video-title"];
    var tags =  video["video-tags"];
    var desc =  video["video-desc"];
    var url =  video["video-url"];
    
    console.log(i + " : " + title + " : " + tags + " : " + desc + " : " + url);
}

Answer №2

Check out this code snippet!

var exampleArray = {
"data":
    [   {
            "data-title": "sampletitle",
            "data-tags": "tag1, tag2, tag3",
            "data-desc": "sample-desc",
            "data-link": "https://www.youtube.com/watch?v=<redacted>"
        }, 
        {
            "data-title": "sampletitle2",
            "data-tags": "tag1, tag2, tag3",
            "data-desc": "sample-desc-2",
            "data-link": "https://www.youtube.com/watch?v=<redacted>"
        }
    ]
};


alert(exampleArray["data"][0]["data-title"])

for(var i=0; i<exampleArray["data"].length; i++){
    alert( exampleArray["data"][i]["data-title"] );
}

Here's the link to view it on JSFiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

A guide to serializing declarative links using Jersey and Jackson

In my project, I have implemented declarative linking. The configuration for my Jackson mapper is as follows: final ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); mapper.configure(MapperFea ...

Ways to eliminate submenu tooltips

Whenever I hover over a menu item with submenu pages in the wordpress backend, a "tooltip" pops up showing each submenu page. How can I remove these tooltips? I have attempted to remove the wp-has-submenu style class, which somewhat works. The tooltip no ...

What is the purpose of using route('next') within ExpressJS?

In the documentation it states: You can have multiple callback functions that act as middleware and can invoke next('route') to skip the remaining route callbacks. This is useful for setting pre-conditions on a route and then passing control t ...

Is it advisable to send an object as an argument in a function?

Here's the code snippet I'm working with: const failure1 = false; const failure2 = false; function callbackFunction(callback, errorCallback) { if (failure1) { errorCallback({ name: 'Negative event1 occurred', ...

Verify the value of the variable matches the key of the JavaScript object array and retrieve the corresponding value

array = { event: [{ key: "value", lbl: "value" }], event1: [{ key: "value", lbl: "value" }] var variable; if(variable in array){ //need to handle this case } I am looking for a function that takes the name of an ar ...

After performing an action with Redux, the error message ""Cannot access properties of 'undefined'" is displayed

I am currently developing a Shopping List App using React/Redux. I am facing issues with removing items from a list. When I trigger the 'removeItem' action, the page no longer recognizes the object that represents the list (which was originally s ...

Transform this color matching game into an image matching game using JavaScript and jQuery

I have a color matching game that I would like to enhance by matching background-images instead of just background-colors. However, I am facing difficulties in making this change. For instance, instead of matching the color red with the text "red," I wan ...

Is there a distinction in invoking a service through reference or directly in Dependency Injection?

QUERY: Are there any discernible differences between the two instances of utilizing a factory service? Instance 1: angular.module('ramenBattleNetworkApp') .controller('MainCtrl', function ($scope, Helpers) { var testArray = [1 ...

Retrieving saved data from LocalStorage upon page reload

<div ng-repeat="section in filterSections"> <h4>{{ section.title }}</h4> <div class="checkbox" ng-click="loaderStart()" ng-if="section.control == 'checkbox'" ng-repeat="option in section.options"> <label ...

Utilizing a dropdown list in HTML to dynamically change images

On my HTML page, I have implemented a dropdown list box. My objective is to change an image and update a label based on the selection made from the dropdown list box. I already have an array called 'temp' which represents the number of items. The ...

Is there a way to automatically play videos without any audio?

Is there a way for my video to automatically start playing when the page loads, without sound? I want it to function similar to the video on this webpage: . I've experimented with various jQuery, JavaScript, and CSS techniques from online resources, ...

Incorporating the angular UI router effectively by reusing the same templateUrl and controller multiple times

Exploring the AngularUI Router framework for the first time, I am curious about how to enhance the code snippet below. Everything is functioning well at the moment, but as the project progresses, it will feature 20 questions or more. I want to avoid repea ...

What is the best way to refresh a single component in my application without causing the other components to reload?

I've been working on a review application with Vue.js that fetches random facts from an API (https://uselessfacts.jsph.pl/random.json?language=en) and allows users to provide feedback through radio buttons and text inputs. Once submitted, the feedback ...

Exploring the transition from JavaScript to jQuery

Currently, I have set up an ajax request in combination with JavaScript to fetch data from an external file. The code looks like this: const ajaxRequest = new XMLHttpRequest(); const handleResponse = function() { if (ajaxRequest.readyState === 4) { ...

Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS. module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'bab ...

Is there a way to update a div element with an image without having to refresh

Currently working on a project for my studies where I am reading the x and y coordinates from a touch pad and drawing it in real time using PHP. I have created a draw page that takes these coordinates and displays them on an image, which is then shown on ...

Assistance required: Click on the button to select and copy all text within the specified paragraph ID

Hey there! I've got a div with a dropdown menu that reveals text and images based on the selected option. What I want to achieve is having a button that allows users to copy all the content inside the div. Below is my sample code for the div dropdown ...

Issues encountered with making JSONP requests

Hey there, I'm a bit stuck and need some help figuring out what's going wrong. Sometimes a fresh perspective can make all the difference. So, here's the situation: I'm making a JSONP request using jQuery from one domain () to a PHP scri ...

How can you update the background image of a particular div using the 'onclick' feature in React.JS?

Thank you for helping me out here. I'm currently working with ReactJS and facing a challenge where I need to change the background of a div from a color to a specific image URL upon clicking a button in a modal. Despite my efforts, I keep encountering ...