1
angular.toJson( obj, pretty );
angular.fromJson( json );

vs

JSON.stringify( obj )
JSON.parse( json )

I used to use native ones, but started to use angular ones for consistency. Any other reasons to use those?

1 Answer 1

3

My first thought was it's related to some test purposes(same case with using $window instead of window). But after looking into source code: https://github.com/angular/angular.js/blob/master/src/Angular.js#L977

function toJson(obj, pretty) {
  if (typeof obj === 'undefined') return undefined;
  if (!isNumber(pretty)) {
    pretty = pretty ? 2 : null;
  }
  return JSON.stringify(obj, toJsonReplacer, pretty);
}

Looks like it's a simple wrap for case with undefined object as param.

same for fromJson: https://github.com/angular/angular.js/blob/master/src/Angular.js#L998

function fromJson(json) {
  return isString(json)
      ? JSON.parse(json)
      : json;
}

so, generally, it's just to remove that checking from app code into framework code.

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

Comments

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.