Struggling to retrieve variables from JSON response in JavaScript

While working on my project, I encountered an issue with accessing an array inside the response object from an API call using AJAX. Despite numerous attempts, I am unable to retrieve the 'quantity' value of the 'expert' object from the response. It seems like a basic task, yet when I try to directly access and log the particular value in the console, it appears as undefined.

Here is a snippet of my response object:

{
    format: "small",
    _links: {
        self: {
            href: "http://www-*******.net/v1/trading/exchange"
        }
},
    _embedded: {
        exchangeData: [  
                server: {
                     time: "10:01",
                     date: "08.12.2014"
                },
                expert: {
                quantity: "48,069",
                country: {
                ..................

The variable that I am trying to access is the 'quantity' value within the 'expert' object. Initially, I attempted to retrieve it using this code:

response._embedded.exchangeData['expert'].quantity

Despite following this approach, the desired value is not being returned. Is this method correct? Accessing such data should typically be simple, so I'm puzzled by this challenge. Thank you for any assistance.

Answer №1

JSON brackets serve as a way to define arrays, like []. An array example would be ["a", "b", "c"], where elements are accessed using a numeric offset such as response[1].

On the other hand, curly braces represent objects (similar to hash tables in different languages), for instance

{"first": "a", "second": "b", "third": "c"}
. Objects are accessed by their property names like response.first.

The syntax is fairly straightforward, you can find more details in the JSON specification here.

In this particular scenario, the correct JSON structure should be:

{
    "_embedded": {
        "exchangeData": { 
            "server": {
                 "time": "10:01",
                 "date": "08.12.2014"
            },
            "expert": {
                "quantity": "48,069",
                "country": {

Note that now there's a curly brace after exchangeData, not a regular bracket. You would access it with:

response._embedded.exchangeData.expert.quantity

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

The git clone operation encounters a problem with the error message: unable to connect, connection refused on localhost port 80

Currently for my project, I'm utilizing isomorphic-git. However, when I try to implement the git.clone function, I encounter the error message Error: connect ECONNREFUSED 127.0.0.1:80. To provide an example of what I am attempting to achieve: import ...

Potential Javascript timing problem encountered during webpage initialization – involving the implementation of a dynamic bootstrap progress

I have limited knowledge of javascript, but I stumbled upon this amazing fiddle that I would like to incorporate into my project: http://jsfiddle.net/5w5ku/1/ The issue I am facing is that I want it to persist for a duration of ten minutes. Despite atte ...

Dynamic blog posts experiencing issues with syntax highlighting feature

I am currently developing a blog using Vue and have decided to incorporate syntax highlighting for the code snippets in my posts by utilizing vue-highlightjs. In order to write the content of my blog posts, I am simply using a textarea within my admin pane ...

I'm curious about the process behind this. Can I copy a Figma component from a website and transfer it into my

Check out this site for an example: Interested in how uikit.co/explore functions? By hovering over any file, a copy button will appear allowing you to easily paste it into your Figma artboard. Want to know how this works and how to implement it on your o ...

What is the best way to transfer information from a server running Express.js to a client using React.js?

When using Express.js, I have the ability to send an HTML file that includes a React component. app.get('/index', function(req, res) { res.sendFile(path.join(__dirname + '/src/index.html')); }); Suppose I want to send a uniqu ...

Tips for implementing cacheable JSON in HTML

Is there a way to access the data stored in an HTML5 file, specifically in the header section like this: <script type="application/json" src="data.json"> Many have recommended using $.get("data.json"), but that requires loading the data each time. ...

Show different values in Array arranged in Table format with the help of Ajax code

Check out the code I have attempted below: <script type="text/javascript"> $('#doctorselected').on('change', function(e){ console.log(e); var doctorid = e.target.value; var url = '{{URL::to('getdoc ...

Implementing a click event listener on an iframe that has been dynamically generated within another iframe

Below is the code I used to attach a click event to an iframe: $("#myframe").load(function() { $(this.contentWindow.document).on('click', function() { alert("It's working properly"); }); }) Everything seems to be working co ...

Assign tags using a variable within a loop

Consider the scenario where I need to generate a list of li elements: {map(listItems, (obj,i) => <li key={i}> <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} > <i c ...

Can the ThreeJS element be seen?

I am facing a challenge in my ThreeJS application where the view automatically centers on an object if it is close to the center of the view and closer than a specified distance. While I have information about the latitude and longitude of all objects and ...

Having trouble resolving the BooksAPI in my code, can anyone help?

I've been trying to troubleshoot this problem, but I can't seem to find a solution. I'm working on a web application for book reading that allows users to organize books they have read, want to read, and are currently reading. On the search ...

Align the number of an Unordered List to the left

Exploring UN-ordered lists in HTML has led me to wonder if it's possible for dynamically generated ul tags to display like this: * Hello * Hi * Bi * Name * Ron * Mat * Cloth * Color * Red When I ...

Even though setState is supposed to update the state and trigger a render, it's not showing up in the view for some

My React app consists of a simple word/definition feature. There is an edit box that appears for users to change the definition when they click on "edit". Even though I call getGlossary() to update the new definition in the state, I can see the changes in ...

Creating a Duplicate of the Parent Element and its Child Elements using jQuery

Here is a code snippet I have that adds a new paragraph when a button is clicked. Currently, the script clones the "sub" div and appends it to the "main" div. However, the issue is that it only copies the content of the "inner" div within the "sub" div ins ...

Enhancing data interpretation using jquery for json data

Is there a way to enhance this? I would like to streamline it, possibly using a loop because in the future I may need to display more than just 10 questions. I attempted to utilize variables with strings instead of "idX" but encountered issues. I prefer to ...

Constructing a table using an array in React

I need assistance with creating a table based on salary data for different sectors. I have an array with example data that includes currencies and sectors. const data=[ ['Euro','Tech'], ['USD','Tech'], ['GBX&apo ...

Discovering Information using AJAX in Laravel

I have created an AJAX code that is supposed to display data from the database in a table based on the input in a textbox. However, I am facing an issue where the data is not changing when I type something in the textbox. Below is the code snippet: <sc ...

Checking for null values using the "and/or" syntax

While reading an article on special events in jQuery, I came across a syntax that was unfamiliar to me: var threshold = data && data.threshold || 1 I have previously encountered the following: var threshold = data.threshold || 1 As far as I kno ...

What is the functionality of named function expressions?

After coming across an intriguing example in the book labeled as a "named function expression," I was curious to delve into its mechanics. While the authors mentioned it's not commonly seen, I found it fascinating. The process of declaring the functi ...

What happens when a client receives a redirect response in ASPX forms?

When a response is received from the server to redirect in ASPX forms using the AJAX control toolkit, what exactly happens from the client's perspective? 25|pageRedirect||/path/to/somepage.aspx| Does the client simply trigger a GET request for the r ...