Decoding JSON data in AngularJS

A json object has a key named lastLogin which holds a string value.

I am attempting to display the names John and Blake.

$scope._users = [{
        "User": {
            "userid": "dummy",
            "lastlogin": "{\"employees\":[{\"firstName\":\"John\"},   {\"firstName\":\"Blake\"}]}",
        }
    }];

Link to JSFIDDLE for reference

Any assistance on this matter would be highly appreciated.

Answer №1

Give this a try:

Example

<div ng-controller="MyCtrl">
    <div ng-repeat="user in _users" ng-init="myInfo=parJson(user.User.lastlogin)">
        <div ng-repeat="emp in myInfo.employees">{{emp.firstName}}</div>
    </div>
</div>

Controller

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

function MyCtrl($scope) {
    $scope.getName = function (user) {
        return "Names";
    };

    $scope._users = [{
        "User": {
            "userid": "dummy",
                "lastlogin": "{\"employees\":[{\"firstName\":\"John\"},                   {\"firstName\":\"Blake\"}]}",
        }
    }];
    $scope.parJson = function (json) {
        return JSON.parse(json);
    }
    //console.log(JSON.parse($scope._users[0].User.lastlogin));
}

DEMO

You can also utilize angular.fromJson.

Here is an alternative method:

$scope.parJson = function (json) {
   return angular.fromJson(json);
}

DEMO

Answer №2

When trying to properly parse the data

"lastlogin": "{\"employees\":[{\"firstName\":\"John\"},   {\"firstName\":\"Blake\"}]}"
, it is recommended to utilize the following code:

angular.fromJson(User.lastLogin);

Ensure that you provide the inner object, lastlogin, to the method in order for it to effectively remove any invalid characters like \ and " from the JSON data.

Answer №3

I found a straightforward solution by using an angular filter.

Let's say you have a variable named category with the value

"{\"name\": \"Pankaj\" }"
. To display the value Pankaj, you can apply filters in the following manner.

<p>{{ category | nameFilter : category }}</p>

The filter function looks like this:

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

.filter('nameFilter', function() {
    return function(input, total) {
        return JSON.parse(input).name;
    };
})

Remember to include this file in the main index.html and pass it in the app.js route.

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

Is there a way to bring my popup closer to my button?

Check out my jsfiddle example here: https://jsfiddle.net/annahisenberg/ft10ersb/34/ Currently, I have the following code: <div id="more_options_popup" style={{ left: this.ref.current.offsetLeft - 140 + "px", top: this.ref.current.offsetTo ...

How to troubleshoot syntax errors when using the delete function in Three.js within Eclipse

When using the Javascript Library Three.js, it is important to note that the delete keyword can be used as an object property. While this is valid under ECMAScript 5 standards, Eclipse currently only supports ECMA 3. As stated in the Mozilla reference, re ...

What is the best way to conceal content within a URL while still transmitting it to the server using node.js and express?

I have been trying to figure out how to hide certain content from the URL, but still need to send that information to the server in my Express app. So far, I haven't found any solutions that work. For example, if I have a URL like www.abc.com/viewblo ...

I am receiving a high volume of row data from the server. What is the best way to present this information on a redirected page?

There is a scenario where Page 1 receives a substantial amount of row data in JSON format from the server. The goal is to present this information on Page 2, which will be accessed by clicking on Page 1. To accomplish this task, JavaScript/jQuery and PHP ...

Can you attach a jQuery function to multiple CSS selectors at once?

Is it feasible to bind a mouseout call to two CSS selectors in order to trigger another action when the mouse moves away from both elements simultaneously? ...

Sending data from an Angular application using AJAX to FormSpree.io

Currently, I am using a jQuery script to send ajax requests to for static form submission. The documentation provided by FormSpree suggests the following approach: $.ajax({ url: "//formspree.io/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Trouble retrieving all rows from mySQL to JSON Object, only receiving the first

In this snippet: $sql ="SELECT * FROM parcours"; $r = mysqli_query($con,$sql); $result = array(); while($res = mysqli_fetch_array($r)){ $result[] = $res; } echo json_encode(array("result"=>$result)); Only the first row of my database query is being ...

Is there a promise specified in the render function of Express node.js?

I have successfully rendered my index.html page, but now I need to send additional data via sockets. To do this effectively, I require a promise for the rendering process. Currently, the code is running synchronously, causing the socket data to be overwrit ...

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to ...

Traversing data in SQL Server that has been transmitted from Angular AJAX requests

Here is a snippet of the sample data being sent: { "Demo":"A 25-54", "Headlines": { "0":"Headline one", "1":"Headline two" } } This is how the post request is structured: $http({ method : 'POST', url : &a ...

Is there a way to disable responsiveness on a website?

Currently, I am in the process of developing a responsive style sheet that is live on our website. However, it seems to display poorly on non-desktop devices due to being a work in progress. I am considering using JavaScript to enforce the desktop layout ...

How to display a Bootstrap modal when clicking on buttons within a dynamic loop of <li> tags?

I would like to share a problem I am facing with buttons in 'li' tag loop. When the info button is clicked, a particular modal should open. However, after clicking the button, the modal does not pop up on screen even though the EJS loop is functi ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

Implementing AJAX functionality in Codeigniter modulesTo integrate AJAX capabilities within Codeigniter modules

I am currently working on a webpage using the CodeIgniter framework. I am looking to integrate a 'show more' button that will utilize 'ajax.php' to retrieve data from the database and dynamically display it on the site. I prefer for thi ...

Convert a string to a scope object using Angular

Suppose there is a string with the value 'order.buyer.address.street' and an order object exists on the scope. How can I access the address object from this? Is there any Angular function like $parse, that could help in retrieving the address ob ...

Tips on how to define an ajax request for the PHP section that is being managed

I recently started using ajax calls to retrieve information from php files and I have 7 elements in my html that trigger these calls. I've created 7 separate php files to handle each ajax call, like so: html part: <a style="cursor:pointer;" id="o ...

HTML5 validation fails to activate

Addressing the issue head-on Check out the form I have created: <form action="<?php echo base_url()?>" method="post" id="formfield"> <center> <label>How much? <small>( Minimum of 100 )</small></label&g ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

Error: The module cannot be located due to a recursion issue in resolving within the Angular application

Trying to import my module import { waitProp } from 'wait-prop'; Encountering the following error: ERROR in ./src/app/qr-scanner/qr-scanner.component.ts Module not found: Error: Recursion in resolving Stack: resolve: (/Users/gkucmierz/workspac ...

Having trouble with linking an external JavaScript file inside the head tag?

I've connected my script.js file to my index.html file, and both files are located in the same directory. I initially linked the script.js file in the <head> section, but it wasn't working as expected. Upon checking the console, I encounter ...