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

Problem with Onsen UI navigation: It is not possible to provide a "ons-page" element to "ons-navigator" when attempting to navigate back to the initial page

Hi, I am having trouble with navigation using Onsen UI. Here is the structure of my app: start.html: This is the first page that appears and it contains a navigator. Clicking on the start button will open page1.html page1.html: Performs an action that op ...

Removing the Yellow Highlight on Input Field Following Email Autocomplete in Chrome

My username-password form is styled and working perfectly, but there's an issue that arises when I log in multiple times. Chrome automatically fills in my email, turning the username textbox yellow. It doesn't seem to happen with Firefox or Safar ...

Convert a CSV file into JSON format using RxJava2

[UPDATED] Greetings I am faced with the task of converting the data from a CSV file into JSON format based on a Java class, using RxJava2. To illustrate, here is an example of how the CSV file is structured: 1,John,Smith The Java class called User has ...

The function os.platform in React and Electron mistakenly identifies the browser as the operating system instead of the actual OS

In my quest to locate the appdata folder for the application, I encountered a challenge where each operating system has a different path for the appdata or application support folder. To address this, I attempted to identify the OS type in order to deter ...

Creating dynamic animations for your elements with AJAX

How can I apply animation to an element as soon as it appears? I want others with the same properties to remain unaffected. Here is my approach: $.each(data, function(i, obj) { if(obj['Ping'] == "FALSE"){ ...

The variable req.body.Dates has not been declared

I am currently working on a project that involves dynamically populating two drop down menus using SQL Server. Depending on the selected items, I need to load a specific ejs template using AJAX. My goal is to load data based on the selected criteria. For e ...

Is there a reason why the JSX select element does not automatically select the option (implementing 'selected')? I'm unsure if I am overlooking something

In my HTML, I have a snippet of code that defines a custom <SelectField> component using a <select> tag like this: export default function SelectField(props) { /* PARAMETERS: - fieldname (String) - fieldID (String) - options (A ...

Error: Attempting to access the 'client' property of an undefined object

I'm currently working on a basic discord.js bot. Below is the code snippet that generates an embed: const Discord = require('discord.js') require('dotenv/config') const bot = new Discord.Client(); const token = process.env.TOKEN ...

What is the best way to trigger a javascript modal to open automatically after a specific duration

Let's take an instance where my modal has the ID #modal1. It usually appears through a button-based action. ...

Adding specific props, such as fullWidth, at a certain width, like 'sm', in Material UI React

My goal is to include the fullWidth prop when the screen reaches a size of 600px or greater, which is equivalent to the breakpoint sm. I attempted to implement the following code, but unfortunately, it does not seem to be functioning as intended. [theme ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...

Navigate to a list item once Angular has finished rendering the element

I need to make sure the chat box automatically scrolls to the last message displayed. Here is how I am currently attempting this: akiRepair.controller("chatCtrl", ['$scope', function($scope){ ... var size = $scope.messages.length; var t ...

Deactivate the typeahead function in the Angular controller based on the user's preference

Is there a way to disable Angular's typeahead feature when a user has a specific checkbox checked in the settings menu (with id = searchSuggestions)? The code provided below seems to work only on a fresh page reload, but not during an active session. ...

Obtaining the sum of two variables from two separate functions results in a value of NaN

Why is it that I'm seeing a NaN result when trying to access a variable in two different functions? This is my code var n_standard = 0; var n_quad = 0; var totalQuad; var totalStandard; var total = totalStandard + totalQuad; ...

Highchart tip: How to create a scrollable chart with only one series and update the x-axis variable through drilldown

Before I pose my question, here is a link to my jsfiddle demo: http://jsfiddle.net/woon123/9155d4z6/1/ $(document).ready(function () { $('#deal_venue_chart').highcharts({ chart: { type: 'column' ...

A TypeError was not captured when attempting to access information about Ionic1 through the angular.module

For the past 48 hours, I've been struggling with an issue that's really getting on my nerves. If anyone knows how to fix this, it would be greatly appreciated: I'm working on an Ionic 1 project and need to make some updates, but nothing I t ...

Unexpected behavior: getElementById returning URL instead of element

I created a function that accepts a thumbnail path as an argument, waits for the bootstrap modal to open, and then assigns the correct path to the thumbnail href attribute within the modal. However, when I use console.log with the element(el), it displays ...

Is utilizing the "sandbox attribute for iframes" a secure practice?

lies an interesting update regarding a technique mentioned in Dean's blog. It seems that the said technique may not work well in Safari based on comments received. Therefore, there is a query about its compatibility with modern browsers, especially Sa ...

Leverage angular-translate to establish placeholder text upon blurring

Just starting out with Angular and facing the challenge of implementing localization in my project. I have a lot of input fields that need their placeholders translated. In my HTML, I'm trying to achieve this: <input type="email" placeholder="{{ & ...

Javascript adds a comma after every postback event

This particular JavaScript code I am incorporating helps in expanding and collapsing nested grid views. <script type="text/javascript"> $("[src*=plus]").live("click", function () { $(this).closest("tr").after("<tr><td></td ...