Extracting precise information from a JSON file using Angular's $http.get

I am struggling with extracting a specific user from a JSON file containing a user list and displaying it on an Angular index page. Despite extensive research, I have been unable to find a satisfactory solution. The user list must remain in a JSON file instead of a JS file.

sampleApp.controller('userInfo', ['$scope', '$http', '$log', '$filter',  function($scope, $http, $log,$filter) {
$scope.results = '';

$http.defaults.headers.common['X-Custom-Header'] = 'Angular.js';

$http.get('data/registered-user-list.json').
    success(function(data, status, headers, config) {
        $scope.results = data;
    })
    .error(function(data, status, headers, config) {
        // log error
    });
}]);

The JSON file:

{ "results": [
{
  "usernumber": "1",
  "userid": "manojsoni",
  "userpassword": "password",
  "useremail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2dfd3dcddd8c1dddcdb9cdddcdedbdcd7f2d5dfd3dbde9cd1dddf">[email protected]</a>",
  "timestamp": "1:30pm",
  "datestampe": "25/01/2016"
},
{
  "usernumber": "2",
  "userid": "jasmeet",
  "userpassword": "password",
  "useremail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="046e657769616170446a65636576766b2a676b69">[email protected]</a>",
  "timestamp": "1:30pm",
  "datestampe": "25/01/2016"
},
{
  "usernumber": "3",
  "userid": "manoj30dec",
  "userpassword": "password",
  "useremail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066b6768696c286d736b677446686761677474692865696b">[email protected]</a>",
  "timestamp": "1:30pm",
  "datestampe": "25/01/2016"
},
{
  "usernumber": "4",
  "userid": "lavish",
  "userpassword": "password",
  "useremail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f232e39263c27613c272e3d222e0f212e282e3d3d20612c2022">[email protected]</a>",
  "timestamp": "1:30pm",
  "datestampe": "25/01/2016"
}    
]}

Answer №1

$http.get('data.json'). //json file path
        success(function(data, status, headers, config) {
            alert("Success");
           $scope.resutls = data;
        }).
        error(function(data, status, headers, config) {
            alert("Error");
          // log error
        });

Check out my response to a similar question here

Accessing and displaying JSON data via Http Get request

Lastly, iterate through the results to extract the desired information.

Answer №2

Please specify the criteria for filtering the user.


Caution! The use of success and error with $http is outdated, replace with then instead!

Deprecation Notice

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

// I will update this function once more details are provided
var getData = function(users){
  for(var i in users{
    if(users[i]["theFieldYouWant"] == theValueYouWant){
        return users[i];
    }   
  }
}

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available
            $scope.results = getData(response);
        },
        function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        }
    );

Answer №3

here is an example of how to utilize this method

$http.get('data.json').then(function(response) {
    console.log(response);
    $scope.results = response;
},
function(error) {
    $scope.results = [];
    console.log(error);
});

Answer №4

The use of success and error methods have been phased out.

Instead, you can utilize the 'then' function

$http.get('data/registered-user-list.json').then(function(response) {
    if (response.status == 200) {
        $scope.results = data;
    } else {
        // log error
    }
});

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

Ensure the initial value in the dropdown menu is automatically set to the first value in VueJs

How can I set the first value of my time object as the default value for my dropdown in Vue? I want the first value to be pre-selected when a user enters the website, but currently only display the value without actually selecting it. time Object:- { &quo ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...

Trouble with Setting Up the Email Address for the 'File a Complaint' Form in WordPress

I am currently in the process of integrating a 'Complaint Registration Form' on my WordPress site. This form enables users to input their name, email address, order ID, and reason for filing a complaint. Once submitted, the details are forwarded ...

declaring a variable in JSP and incorporating it into jQuery

How can I retrieve the size of options in a route object and store it in a variable in JSP? I then need to access this variable in jQuery. Any suggestions on how to achieve this? JSP code : <%!int loopSize = routes.get(0).getOptions().size(); %> ...

Is it possible to utilize setTimeout to demonstrate the execution of a while loop visually?

I am working on a function that generates random numbers between 1 and 6 until it matches a target value of 3. I want to create a visual effect where each randomly generated number is displayed on the page, but I'm facing some challenges with delays. ...

Error encountered: The EVM has reverted the transaction

After successfully deploying this basic smart contract using Remix, I encountered an issue when trying to interact with it through web3.js in my upcoming app. I used the evm version: paris for deployment and everything worked smoothly on Remix IDE. Here i ...

Implementing Expected Conditions using JavaScript calls in Selenium can greatly improve the reliability and efficiency of

Below is my Python Selenium code that downloads a shapefile of Rio de Janeiro. import time, os from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.web ...

Communicating between iframes and parent elements via events

I'm trying to trigger an event in my iframe using the following code: $('body').trigger('my_event'); However, I want to bind this event on my main page that contains the iframe like this: $('iframe').find('body&ap ...

Creating a unique data attribute in Alpine.js - A step-by-step guide

I am looking to establish a custom attribute and modify the value when clicked. This is my current setup: <div x-data="{ colorred = true }"> <div @click="colorred = !colorred">set red state</div> </div> I ...

Filter your DataTables columns by searching for text within a specific range

Below is the code for implementing a text range filter in SQL: function fnCreateTextRangeInput(oTable) { //var currentFilter = oTable.fnSettings().aoPreSearchCols[i].sSearch; th.html(_fnRangeLabelPart(0)); var sFromId = oTable. ...

When executing class methods, Ember.js encounters errors stating "method does not exist."

I am facing a situation where I need to trigger a model reload when a user clicks a refresh button. In the past, I successfully implemented this with Ember-Model. However, since migrating to Ember-Data, I am encountering an error when attempting to execute ...

What is the best way to eliminate whitespaces and newlines when using "document.execCommand("copy")" function?

I'm currently working on a code that allows users to copy highlighted text without using the keyboard or right-clicking. I also need to remove any extra spaces or line breaks using regex after the text is selected. However, I am facing some issues wit ...

Display notification only on certain days

I'm trying to create an alert that only pops up on specific days, but I can't seem to figure it out $(document).ready(function () { $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday&a ...

Navigating to a new URL after submitting a form in React

Hello, I am new to React and have created a form that successfully sends data to Firebase. However, after submitting the form, I would like to redirect to /thankyou.html which is outside of the React app. Can someone please guide me on how to achieve this ...

Is there a way to create an input field that accepts only numbers and behaves like a password field simultaneously?

I am attempting to develop an input field for entering a PIN. I would like the PIN to be masked on mobile devices, similar to how passwords are obscured in password input fields. I came across a suggestion on stackoverflow regarding this, but unfortunately ...

Developing a custom AngularJS directive for uploading files as base64

I am interested in creating a directive that handles file uploads (base64 of a file) using ng-flow. I was able to get the directive working without using ngModel, but since I need to use it within a form, it would be better to include it (and also have the ...

How to submit a form using AngularJS on an ASP.NET webpage

Having some frustrations with asp.net... I have a basic website with a form in my master page that needs to be server-side because of the controls I use. Now, I want to incorporate angularjs into a simple page on this site. My goal is to only submit the fo ...

eliminate an element from the dictionary

This JSON data is classified as a java.util.HashMap object. jsonRequest=[noOfMembers:2, coverageYear:2017, zipCode:99123, premiumList:[[Premium:203.05, Id:1000101], [Premium:205.36, Id:1000102], [Premium:207.67, Id:1000103], [Premium:209.98, Id:1000104], ...

Unload pre-loaded JavaScript documents

Two javascript files are included in a popup (simple div) created using ajax. <script type="text/javascript" src="<?php echo JS ?>pm.js"></script> <script type="text/javascript" src="<?php echo JS ?>chat.js"></script> ...

Exception still present in registered Jackson LocalDate module

When trying to serialize a list with various objects of the class Person, each containing a firstname, lastname, and a birthday, I encountered an issue. After researching on this forum, I discovered that I needed to register the jsr.310.JavaTimeModule in o ...