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

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date. getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) { var date = new Date(millisSinceEpoch); if (d ...

The Firestore query for viewing resources is currently not functioning as expected due to issues with

I'm currently working on implementing the "read" Rules from an array, following the guidelines in this blog post var db = firebase.firestore(); db.collection("_users").where("viewers", "array-contains", myUID) .get() .then((querySnapshot ...

Sending an incorrect value to the data variable

Apologies for my limited proficiency in English, Hello, I am new to Vue and struggling with an issue that I can't seem to resolve. I am fetching art data from an API (a simple list of dictionaries), and then creating a multi-array structure (list of l ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

How can I assign multiple names to a JsonProperty in C#?

[XmlElement("A", Type = typeof(MyModelA)), XmlElement("B", Type = typeof(MyModelB))] public List<object> context{ get; set; } Although this approach works, I would like to switch to using JsonProperty instead: [JsonProperty("A", ItemConverterType ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...

I am experiencing difficulties in accessing the DOM

I have implemented jQuery $.ajax to dynamically load data into table rows as shown below: <table id='row-data'> <tr><td>1001</td></tr> <tr><td>1322</td></tr> <tr><td>15 ...

Choose2 incorporate on change

I have a Laravel project where I am using the vuexy theme. I've been trying to add an onchange event to my select2 input, but so far I haven't had any success. Here is my select2 input: <div class="col-12 mb-2"> <label class ...

Obtain Beautifully Formatted JSON from MVC 3's JsonResult

Scenerio Programming Language: C# Platform Version: Microsoft .Net Framework 4.0 Operating System: Windows 7 Professional (64-bit) Constraints: Microsoft MVC.Net 3.0 Issue Description In my current development tasks, I often need to inspect JSON ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Reverse the action and postpone the Ajax call for a specified time or until the next action occurs

How can I implement a setup and undo feature for my ajax calls that allows users to delay the call for a set amount of time and abort it if needed? I also want to be able to stop the delay and proceed with the most recent ajax call if another action is tri ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

What could be causing getStaticProps to receive an incorrect slug value?

Currently, I am encountering an issue with obtaining the correct slug in getStaticProps(). My goal is to retrieve the translated slug for a specific page (for example: the about page). The getStaticPaths() function is able to generate the correct object. ...

Can a static text be displayed randomly using Javascript?

What I'm searching for is a unique text display feature that's different from scrolling. I envision a subtle fade in/out effect, but it's not necessary. The main goal is to fit within a small area on a website with limited vertical space - ...