RoyBar
RoyBar

Reputation: 149

How can i use JSON stringify in Angular?

i'm newbie to Angular. I'm trying to get Json data which written like that :

id:1,
name: "Friends",
type: "Group",

Now, i know i can't use this kind of data unless i add double quotes - like that (it's the only way it is working):

"id":1,
"name": "Friends",
"type": "Group",

What is the best way to parse JSON in Angular?

I've tried to combine JS , but it didn't work :

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

    $http.get('http://localhost/Angular-Http-exercise/db.json')
        .then(function(response) {
            $scope.myData = function() {

            return JSON.stringify(response.data)
        };

        $log.info(response.data.name);
    });
});

Upvotes: 2

Views: 32587

Answers (2)

Yaser
Yaser

Reputation: 5719

You can use angular.fromJson and angular.toJson for that purpose:

scope.myData = function(){
       return angular.fromJson(response.data);   
}

However JSON is a global variable and you should have access to it, since angular uses the same.

https://docs.angularjs.org/api/ng/function/angular.fromJson https://docs.angularjs.org/api/ng/function/angular.toJson

Upvotes: 5

Naguib Ihab
Naguib Ihab

Reputation: 4506

Roy, your question is What is the best way to parse JSON in Angular? JSON will not differ from one framework/language to another and there's no best way to write JSON.

If you want to see if your JSON is formatted correctly check out tools like: https://jsonformatter.curiousconcept.com/

Upvotes: 0

Related Questions