having trouble retrieving data from JSON array using JavaScript

I am having trouble fetching the JSON value to determine if the person in the photo is wearing glasses. The value is spread across four arrays: photos, tags, attributes, and glasses. My goal is to check if the value "value" is either true or false. I have attempted to use alert() to test if the value is fetched, but nothing is being displayed. I am unsure of which part of my code is incorrect.

My JavaScript code to fetch the JSON value is shown below:

var facesDet = $.getJSON( APIdetect, function() {
  console.log( "success" );
  console.log(facesDet);
})

.done(function (facesDet, tid) {
    var VALUEIWANT = facesDet.photos[0].tags[0].attributes[0].gender[0].value;

});

Here is the structure of the JSON value:

{
"photos" : [
    {
        "url" : "http://tinyurl.com/673cksr",
        "pid" : "F@0c95576847e9cd7123f1e304476b59ae_59ec9bb2ad15f",
        "width" : 375,
        "height" : 409,
        "tags" : [
            {
                "tid" : "TEMP_F@0c95576847e9cd7123f1e304b1dcbe53_59ec9bb2ad15f_56.53_40.83_0_1",
                "recognizable" : true,
                "confirmed" : false,
                "manual" : false,
                "width" : 30.67,
                "height" : 28.12,
                "center" : { "x" : 56.53, "y" : 40.83},
                "eye_left" : { "x" : 66.93, "y" : 33.99},
                "eye_right" : { "x" : 51.73, "y" : 33.99},
                "yaw" : -16,
                "roll" : 0,
                "pitch" : 0,
                "attributes" : {
                    "face" : { "value" : "true", "confidence" : 82 },
                    "gender" : { "value" : "female", "confidence" : 80 },
                    "glasses":{"value" : "true", "confidence" : 100},
                    "dark_glasses":{"value" : "true", "confidence" : 72},
                    "smiling":{"value" : "false", "confidence" : 35}
                }
            }
        ]
    }
],
"status" : "success",
"usage" : {
    "used" : 1,
    "remaining" : 99,
    "limit" : 100,
    "reset_time_text" : "Fri, 21 September 2012 12:57:19 +0000",
    "reset_time" : 1348232239
}
}

Answer №1

Attempting to extract gender information as if it were an array:

var DESIRED_VALUE = facesDet.photos[0].tags[0].attributes[0].gender[0].value;

However, in the JSON data, gender is an object, so the correct syntax is:

var DESIRED_VALUE = facesDet.photos[0].tags[0].attributes.gender.value;

Answer №2

Your method of access is incorrect. You are mistakenly treating an object as an array.

var DESIREDVALUE = facesDet.photos[0].tags[0].attributes[0].gender[0].value;
//                                                              ^^^  and  ^^^

Correct way to access:

var DESIREDVALUE = facesDet.photos[0].tags[0].attributes.gender.value;

Data:

"attributes" : {
    "face" : { "value" : "true", "confidence" : 82 },
    "gender" : { "value" : "female", "confidence" : 80 },
    "glasses":{"value" : "true", "confidence" : 100},
    "dark_glasses":{"value" : "true", "confidence" : 72},
    "smiling":{"value" : "false", "confidence" : 35}
}

Answer №3

Give this a shot!

facesDet.images[0].tags[0].attributes.gender.value

Answer №4

Instead of directly getting the response, remember that getJSON returns a promise. Use the following code to handle the promise:

$.getJSON( APIdetect, function(facesDet) {
  console.log( "Request successful" );
  console.log(facesDet);
})

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

Developing a Node.js and Express REST API for generating tailored routes for custom fields

I'm currently using node.js and express framework to build my REST API server. One of the features I want to implement is similar to the Facebook graph API, where I can pass specific fields in my API routes like: /me?fields=address,birthday,email,do ...

The Node.js server pauses its listening activities until the promise, which involves an asynchronous function that runs a loop with the goal of making it operate in the background, is

My server code is set up to listen on a specific port: app.listen(PORT, () => { console.log(`Server running on ${PORT}`); }); When a request is received, it is sent to a function for processing: app.get("/", (req, ...

What is the best way to update an element in an array inside a JavaScript object

In my NodeJS code, I have an object structured like this: const jsonData= { "description": "description", "hosts": [ "host1", "host2", "host3" ] } The task at ...

The PHP query that was sent through an AJAX POST request is not being executed correctly

I have a situation where I am working with two pages: Page 1: <input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/> <input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/& ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...

Vue Dev Tools is not updating data in Ionic Vue 3

There seems to be an issue with the updating of Reactive and Ref data in Vue Dev Tools when changes are made in an input field bound with v-model within a form. The updated data is only visible when I interact with another component and then return to the ...

How to effectively manage time and regularly execute queries every second using Node.js?

Currently working on developing a web software using node js with an Mssql database. There is a table in the database that includes a datetime value and a bit value. The bit value remains at 0 until the real-time matches the datetime value, at which point ...

Rails application encountering a problem with JSON data retrieval

Encountering an issue with Rails and Devise where I get logged out every time I request a .json extension file. For instance, if I visit /tables.json to view table data, it shows up fine. But when I navigate back to the root folder, I find myself logged o ...

How do I execute a Next.js script that utilizes `fs` and `sharp` during development with Webpack?

I'm working on creating a basic GIFPlayer that displays a GIF when the play button is clicked, and shows a PNG otherwise: <img className="w-full h-full" src={isPlaying ? gifPath : imgPath} alt={pic.alt} /> Since I only have a GIF file ...

Updating the parameters when clicking on each pagination button: A guide

Does anyone have advice on implementing pagination? I am currently working on loading a datatable with a few records initially. Once the page is loaded, I want to be able to click on pagination buttons like next or any pagination buttons to display a new s ...

JQuery Falters in Responding to Button's Click Action

Forgive me for what may seem like a silly question, but as someone new to JQuery, I have been struggling to figure out why my function is not displaying an alert when the button is clicked. Despite thorough research on Google, I haven't been able to f ...

Manipulating images separately using the canvas

Currently, I am utilizing an HTML5 canvas to generate a collection of trees alongside their corresponding shadows. My objective is to ensure that each shadow corresponds with the position of a designated light source. While I have successfully drawn each t ...

When the webpage is refreshed, a PHP code embedded within JavaScript is executed instead of waiting for a

This particular code is designed to toggle the chat feature on and off. The issue I am encountering is that it automatically toggles the chat on or off each time the page is refreshed. Ideally, it should only trigger when a user clicks on a specific link ...

Effective ways to retrieve API response data in React JS

I am working on a Spring Boot project which includes an API for user login. When the user name and password are sent through this API, it checks the database for the information. If the data is found, it returns a successful login message; otherwise, it ...

Add integer to an array of strings

Currently, I am utilizing an autocomplete feature and aiming to save the IDs of the selected users. My goal is to store these IDs in a string array, ensuring that all values are unique with no duplicates. I have attempted to push and convert the values u ...

Can you explain the meaning of the ?. operator in JavaScript?

While using react-hook-form, I encountered the ?. operator. Can you explain its meaning? Here's an example of how it works: <span>{errors?.name?.message}</span> The errors variable is obtained from useForm() by destructuring, as shown bel ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Show notifications after being redirected to a new page

My goal is to submit a form and have the page redirected to a different URL upon submission. Currently, everything works as expected, but there is an issue with the timing of the toast message. The toast message appears immediately after the user clicks th ...

Should I consolidate my ajax requests into groups, or should I send each request individually?

Currently working on an ajax project and feeling a bit confused. I have 3 functions that send data to the server, each with its own specific job. Wondering if it's more efficient to group all the ajax requests from these functions into one big reques ...

The `Route` component is expecting a `function` for the `component` prop, but instead it received an `object`

For a while now, I've been grappling with an issue that seems to be unique to me. The problem lies within my component and container setup for the start screen rendering at the initial route. components/DifficultySelection.jsx import React from &apo ...