Retrieving nested JSON object data with Angular's HTTP GET method

Currently, I am attempting to extract a URL from a JSON object that is nested, but I am encountering difficulties accessing the data. I am unsure of the method to retrieve data from a JSON object that is deeply nested.

app.controller('mainCtrl', function($scope, $http) {


$http.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D'www.whitehouse.gov%2Ffacts%2Fjson%2Fall%2Fcollege%2520affordability'&format=json&diagnostics=true").then(function(responce) {
      $scope.status = responce;
      $scope.sortData = responce.data.query.results.json.json.url;
      console.log(responce);
      console.log($scope.sortData);
    });

});

Although I am able to console log the object, I am struggling to extract the URL from the deeply nested object. The JSFiddle link provided below displays the object that is console logged. I appreciate any assistance given.

https://jsfiddle.net/39pwve2x/19/

Answer №1

Here is the updated fiddle link: https://jsfiddle.net/39pwve2x/23/

The URL is contained within a repeating array object in the data structure (the last "json" node). Each "json" in the array has a URL property. If you want to access all the URLs, pass the array to your view and use ng-repeat:

<body ng-app="javascriptTest">
    <div ng-controller="mainCtrl">
        <div ng-repeat="item in sortData">
            {{item.url}}
        </div>
    </div>
</body>

...and in the controller...

var app = angular.module('javascriptTest', []);

app.controller('mainCtrl', function($scope, $http) {
    $http.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D'www.whitehouse.gov%2Ffacts%2Fjson%2Fall%2Fcollege%2520affordability'&format=json&diagnostics=true").then(function(responce) {
      $scope.sortData = responce.data.query.results.json.json;
    });
});

If you only need a single URL, you can specify an index like this. For instance, to get the first URL returned by the data:

$scope.firstUrl = responce.data.query.results.json.json[0].url;

Answer №2

Short Answer

responce.data.query.results.json.json[0].url;

Long Answer

The responce.data.query.results.json.json is an array of objects. Each object is identified by an index that must be specified in order to access it.

If you want to access all the objects in the array, you can use a loop like the one below:

var data = responce.data.query.results.json.json    
for (var i = 0; i < data.length; i++) {
    console.log(data[i].url);
}

https://jsfiddle.net/39pwve2x/22/

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 is the best way to implement asynchronous image loading on hover events in React.js?

You may have come across this type of effect before. A good example can be found here - https://codepen.io/anon/pen/GEmOQy However, I am looking to achieve the same effect in React. While I understand that I can use the componentDidMount method for AJAX c ...

Setting a value programmatically in a Material-UI Autocomplete TextField

In my React application, I am using material-ui Autocomplete and TextField components to allow users to select values from a dropdown list. However, I am looking for a way to programmatically set the input value by clicking a button, without having to choo ...

Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML. function sendData() { var formData = new FormData( document.querySelector("form") ); var xmlHttp = new XMLHttpRequest(); xmlHttp.open("post", "test.php",true); ...

Unexpected behavior occurs when ajax is added to an array for jQuery promise results

In my code, I have an each loop that makes individual AJAX requests and stores them in an array like this: var promises = []; $items.each(function(k, v) { promises.push( $.ajax({ url: ..., .... }) ); }); $.when.app ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

What is the proper way to implement a "for" loop within an "array"?

Appreciate your assistance. Currently, I am in the process of developing a new website and aiming to create a CSV file from an XML-based website. However, I am facing challenges using "for (number...)" within an array. <?php // Set headers for file d ...

Retrieve various objects from separate files using Node.js

Throughout the development of my Node.js project, which I have been working on since my teenage years and consists of a multitude of files, I have initialized numerous objects in the index.js file. This is also where all function calls originate. In order ...

JavaScript post method for JSON data: no input or output values

I am currently developing a page that extracts data from an HTML table consisting of two columns and an index of a form, and then converts it into a JSON string. The intention is to pass this data into PHP for further processing, perform calculations on th ...

Add fresh HTML elements within the ng-repeat loop

I'm struggling to insert new HTML code in the middle of an ng-repeat loop. I've tried using append but it doesn't seem to work. Here is a snippet of my code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/aja ...

Is there a method available to define a custom auto-generated key when inserting an object into Firebase Realtime Database?

I've been working on pushing data to the firebase rtdb and I want to make sure I can easily access it from other places. Here's the code snippet that I'm using to add data to the rtdb: function addStudentHandler(studentData) { fetch( ...

Attempt to retrieve node information using the useStaticQuery method in Gatsby

I am facing an issue where I am trying to retrieve information from GraphQL Gatsby using useStaticQuery, but the data returned is showing as undefined. I am confused as to why this is happening because when I check my http://localhost:8000/___graphql endpo ...

Obtain an array containing the keys of an object

How can I retrieve the keys of a JavaScript object as an array, using either jQuery or pure JavaScript? Is there a more concise approach than this? var data = { 'first' : 'apple', 'second' : 'banana' }; var element ...

Is there a way to transfer a text file from an iPhone application to an ASP.NET platform?

Can anyone assist me with retrieving a text file sent from an iPhone application to my ASP.NET application? HttpContext context = HttpContext.Current; NameValueCollection nvc = context.Request.Form; string file = nvc["text_file"]; I have success ...

Tips for showing values in the Reduce function

Utilizing mapreduce in Hadoop, I have successfully parsed Json data and now I aim to display two string variables within the reduce function. Below is the code snippet I attempted: public static class Map extends Mapper<LongWritable, Text, Text, Text ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

Unveiling the Magic Bytes: Extracting the Image File in Multer for Magic Byte Verification in Express.js

Utilizing the fileFilter option within the multer plugin to determine whether an image should be saved on the server or not. Within the fileFilter function, there is a need to verify the magic bytes of these images in order to ensure they are legitimate a ...

What methods does Angular use to display custom HTML tags in IE9/10 without causing any issues for the browser?

Exploring web components and utilizing customElements.define tends to cause issues in IE9/10. I've noticed that Angular is compatible with IE9/10, and upon inspecting the DOM tree, it seems like Angular successfully displays the custom element tags. ...

The variable (form.onsubmit) remains unset even after assigning a value

function setFormOnSubmit(formName){ if(!formName) return; var form = document[formName]; form.onsubmit = function(){ console.log('This is the onsubmit function'); }; console.log('onsubmit successfully set ...

What is the best way to initiate a function from within another function while working with ReactJS?

Seeking guidance on how to trigger a Redux state change by calling a function from another function using the onClick event. Currently, I am able to invoke the Jammingmenu upon clicking an icon, however, no action is performed or alert displayed. Any assis ...

Solar Flare Malfunction

angular.module('starter') .controller('LoginCtrl', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) { $scope.loginForm = {} $scope.loginError = false; $scope.loginErrorText; ...