Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JSON.parse() use eval() internally? [duplicate]

Does JSON.parse in modern browsers use eval() internally for evaluating and executing the dynamic code?

Because I have been looking through Douglas Crockford's JSON library. It also uses eval() when using parse() but after preprocessing prior to the actual evaluation. Such as:-

  1. A wall against Unicode characters in the code.
  2. A code shows malicious intent.

Do the modern browsers which supports JSON.parse natively perform this or they follow other protocols?

like image 799
pvnarula Avatar asked Jun 10 '13 12:06

pvnarula


1 Answers

No, JSON.parse() doesn't Use eval()

This is by design, as eval() being able to execute any arbitrary JavaScript code you feed it, it could execute things you wouldn't want it to. So JSON.parse() does what it says on the tin: it actually parses the whole string and reconstructs and entire object tree.

JSON.parse is usually delegated to an internal function implemented with "native" code, where "native" means whatever is considered "native" in the context of your browser's javascript engine (could be compiled machine code, could be bytecode for a VM, etc...). I don't think there's any strong requirement on that.

Differences in the Implementations?

JSON (the notation) itself is codified by the RFC4627.

Regarding the implemetation of the JSON object and its methods, all modern browsers implementing should behave the same, as they should follow the same specifications for ECMAScript 5's JSON object. However, there's always the chance for potential defects. For instance, V8 originally contained this nasty bug.

Also, note that the implementation listed in comments above are for you to add JSON.parse() support to browsers that do not support it natively (also known as "these damn old browsers you sometimes need to support"). But it doesn't mean that it's necessarily how they implemented it.

For instance, for Google's V8 implementation used in Chrome, see json.js which invokes native code from json_parser.h.

like image 106
haylem Avatar answered Oct 17 '22 22:10

haylem