Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Refactor isJson() #75

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Angular.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ function isElement(node) {
return node && (node.nodeName || node instanceof JQLite || (jQuery && node instanceof jQuery));
}

function isJson(value) {
return isString(value) && (/^\s*\{/.test(value) && /\}\s*$/.test(value) ||
/^\s*\[/.test(value) && /\]\s*$/.test(value));
}

function HTML(html) {
this.html = html;
}
Expand Down
2 changes: 1 addition & 1 deletion src/services.js
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ angularServiceInject('$xhr', function($browser, $error, $log){
}
$browser.xhr(method, url, post, function(code, response){
try {
if (isString(response) && /^\s*[\[\{]/.exec(response) && /[\}\]]\s*$/.exec(response)) {
if (isJson(response)) {
response = fromJson(response);
}
if (code == 200) {
Expand Down
21 changes: 21 additions & 0 deletions test/AngularSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,24 @@ describe('angularJsConfig', function() {
ie_compat_id: 'ng-ie-compat'});
});
});

describe('isJson', function() {
it('should return false on non-string', function() {
expect(isJson()).toBeFalsy();
expect(isJson({})).toBeFalsy();
expect(isJson([])).toBeFalsy();
expect(isJson(10)).toBeFalsy();
});

it('should return true on strings starting and ending with curly or square brackets', function() {
expect(isJson('{a: "b"}')).toBeTruthy();
expect(isJson('[1, 2, 3]')).toBeTruthy();
expect(isJson('\t\n{a: "b"} ')).toBeTruthy();
expect(isJson(' [1, 2, 3] ')).toBeTruthy();
});

it('should return false on other strings', function() {
expect(isJson('{ ]')).toBeFalsy();
expect(isJson(' abc ')).toBeFalsy();
});
});