G
Garrett Smith
The FAQ mentions JSON, but only for "when do I use eval". That entry is
not focused on a specific task.
An FAQ entry JSON, in contrast, would be focused on a specific task, and
a common one. It would be useful to mention JSON.parse support there.
FAQ Entry Proposal:
| How do I evaluate a JSON response?
|
| An XMLHttpRequest's responseText can be evaluated in a few ways. The
| Function constructor and eval are both widely supported; either can
| be used to evaluate trusted code.
|
| The Function constructor creates a globally-scoped Function. In
| contrast, eval runs in the calling context's scope.
|
| To evaluate code with the Function constructor, you could use:
|
| function evalResponse(responseText) {
| return new Function("return(" + responseText + ");")();
| }
|
| Where supported, JSON.parse may be used.
|
| var NATIVE_JSON_PARSE_SUPPORT = window.JSON &&
| typeof JSON.parse === 'function' &&
| JSON.parse('true').test;
|
| function evalResponse(responseText) {
| if(NATIVE_JSON_PARSE_SUPPORT) {
| try {
| return JSON.parse(responseText);
| } catch(ex) {
| return "Error";
| }
| } else {
| return new Function("return(" + responseText + ")")();
| }
| }
|
| If the argument to JSON.parse is not JSON, a SyntaxError will be
| thrown.
Garrett
not focused on a specific task.
An FAQ entry JSON, in contrast, would be focused on a specific task, and
a common one. It would be useful to mention JSON.parse support there.
FAQ Entry Proposal:
| How do I evaluate a JSON response?
|
| An XMLHttpRequest's responseText can be evaluated in a few ways. The
| Function constructor and eval are both widely supported; either can
| be used to evaluate trusted code.
|
| The Function constructor creates a globally-scoped Function. In
| contrast, eval runs in the calling context's scope.
|
| To evaluate code with the Function constructor, you could use:
|
| function evalResponse(responseText) {
| return new Function("return(" + responseText + ");")();
| }
|
| Where supported, JSON.parse may be used.
|
| var NATIVE_JSON_PARSE_SUPPORT = window.JSON &&
| typeof JSON.parse === 'function' &&
| JSON.parse('true').test;
|
| function evalResponse(responseText) {
| if(NATIVE_JSON_PARSE_SUPPORT) {
| try {
| return JSON.parse(responseText);
| } catch(ex) {
| return "Error";
| }
| } else {
| return new Function("return(" + responseText + ")")();
| }
| }
|
| If the argument to JSON.parse is not JSON, a SyntaxError will be
| thrown.
Garrett