A guide to parsing nested JSON with AngularJS

I am currently working on parsing a nested JSON using AngularJS. Here is an example of the nested JSON structure:

{
  "results": [
    {
      "id": "D1",
      "name": "A",
    },
    {
      "id": "D2",
      "name": "B",
    }
  ]
}

Below is the AngularJS controller that retrieves the JSON data from PHP, but is currently returning [object object] instead of the expected JSON data. Furthermore, when attempting to access the JSON data, it returns an 'undefined' value.

function MyController($scope, $http) {
    $http({
        method: 'GET',
        data: "action=0",
        url: 'a.php'
    }).then(function(data) {
        alert("Hello" +data);    //alerts Hello[object Object]
        $scope.legs = data.results;
        alert($scope.legs);     //alerts undefined
    });

}

Here is the HTML code snippet that attempts to display the JSON data:

<tr ng-repeat="l in legs">
  <td>{{ l.id }}</td>
</tr>

Answer №1

To understand the functionality of $http, visit https://docs.angularjs.org/api/ng/service/$http

When using $http, the response body is not directly returned as a result of the promise. Instead, you will receive an object containing more information about the HTTP request. To access the body or data, you need to utilize the data property:

function MyController($scope, $http) {
    $http({
        method: 'GET',
        data: "action=0",
        url: 'a.php'
    }).then(function(response) {
        $scope.legs = response.data.results;
    });

}

It is important to ensure that your server is properly setting response headers for JSON to enable the response transforms.

Answer №2

To gain a better understanding of $http promises, take a look at the documentation provided here: https://docs.angularjs.org/api/ng/service/$http

One important thing to note is that the successCallback in $http promises receives a response object, not the data directly. This response object contains the actual data that you are looking for. Therefore, you need to access your JSON data from the data property within this response object.

Let's update the code snippet:

}).then(function(response) {
    alert("Hello" + response.data);   
    $scope.legs = response.data.results;
    alert($scope.legs);
});

After making this modification, your $scope.legs will contain the JSON data, allowing ng-repeat to function as expected.

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

Divergent functionality of regular expressions in Internet Explorer and Chrome when handling white spaces

Here is a function that validates input by checking for numbers and no spaces in between: checkInputValidity: function() { var isValid = true; var idNumber = this.getView().byId("iDNumber"); var regex = /^[0-9]+$/; if (idN ...

"Exploring the boundaries: Maximum data constraints for JSON and PHP in

My Android app is functioning properly, sending various details to a PHP webserver using JSON: "PhoneNumber" "ContactName" "CallType" "CallDate" "CallDuration" The app successfully retrieves all this information and the PHP webserver is able to parse it ...

How can I trigger an AJAX request when the value in a dropdown menu is changed?

index.php <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript" src="ajax.js"></script> <a href='one.php' class='ajax'>One</a> <a href='two.php' ...

What is the correct way to assign the products variable to the array retrieved from the API response?

I am currently trying to implement a primeblocks component and I am struggling with v-binding the dataTable to the response I receive from my API. My issue lies in the fact that when I console.log(productData), I am getting an array that contains another ...

Encountering an error when implementing a router object within a TypeScript class in a Node.js environment

I have a Node.js service written in TypeScript. I am currently working on implementing a separate routing layer within the application. In my app.js file, I have the following code: let IndividualRoute= require('./routing/IndividualRoute'); app ...

Include the URL as a parameter in the query when utilizing Tesseract OCR

I have successfully implemented the tesseract ocr, but I am wondering if it is possible to run tesseract with a URL as a parameter. I want to achieve the following: localhost/test.html/?othersite.com/image/image2.jpg Here are some image URLs for demonst ...

How can I enhance a JavaScript Calendar with more features?

I recently acquired a JavaScript and jQuery calendar from CodeCanyon, which can be found here. I am now faced with the task of integrating this calendar into my workplace website. The current calendar on our ASPX-based site is limited to read-only functio ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Populate a 2D array in JavaScript/NodeJS "line by line"

Hey there! I could really use some help with JavaScript/NodeJS arrays. Here is the code I'm working with: let arr = new Array(); arr = { "Username" : var1, "Console" : var2, "Pseudo" : var3, } console.log(arr); The variables var1, var2, ...

Incorporate a variable into a function by integrating it

I'm struggling to accurately calculate the total hours needed based on the method of transportation. This code represents my initial attempt at learning how to code, diving into JavaScript for the first time. Here's my script: $(document).read ...

Loop through an HTML table in order to emphasize variations in cells that contain multiple comparison items

I am interested in highlighting variances between the initial row of a table and all other rows based on columns. I have successfully managed to achieve this when each cell contains only one item/comparison. However, I would like to expand this to include ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Error in Angular ESLint: The key parameter is mandatory

I'm attempting to download a file using the Angular code below, but I consistently receive an error stating Parameter "key" required const headerValues = new HttpHeaders({ 'Content-Type': contentType!, 'Accept': contentTy ...

Using the PUT method in Node.js to set the ID

Need help with setting ID value from frontend apiRoutes.put('/intake', function(req, res) { Intake.findById({id, function(err, intake) { if (err) res.send(err); check : true; intake.save(function(err) { ...

Varying heights based on the screen size

Currently, I am in the process of designing my website and incorporating some wave elements to enhance the background. However, I've encountered some issues when resizing the screen. Specifically, the waves seem to shift with a space between them as t ...

The issue arises when using multiple route files in Route.js, as it hinders the ability to incorporate additional functions within the

After breaking down Route.js into multiple controllers, I'm stuck on why I can't add an extra function to block permissions for viewing the page. // route.js module.exports = function(app, passport) { app.use('/profile&apos ...

Local environment successfully executes API calls, but encounters issues in live environment

My custom-built API in PHP involves a simple GET request to a MariaDB database, fetching records in JSON format. The folder structure is as follows: /api /api/some/read.php /api/some/read2.php /config /config/Database.php /models /models/call.php /models ...