2

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);
    });
});
3
  • 1
    make sure the source is valid json in the first place. If the contents of that file don't validate on jsonlint.com...fix it. Beyond that this question doesn't make much sense Commented Feb 9, 2017 at 23:20
  • charlietfl -thanks Commented Feb 9, 2017 at 23:38
  • The AngularJS $http service automatically parses JSON data. There is no need to do anything., Commented Feb 10, 2017 at 2:38

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

3 Comments

Naguib Ihab - Thanks - All your comments gave me better insights regarding JSON format.
If you found the answer helpful, consider a +1
This is actually incorrect. When using angularjs, always use the inbuilt methods as per accepted answer. These will automatically strip out any non-json characters injected by angular such as $variables and other tracking info angular will put in the json if for instance you bind an array of objects to an ng-repeat. If you just try to use JSON.stringify in your controllers and then send this server side, these artifacts will remain in the json and potentially break your app when for instance sharing json with other apps or doing a JSON.Deserialize (C#) on the server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.