javascript - Why JSON.parse cant detect if argument is already in JSON format -
as know json.parse parses stringified json, if variable json , try json.parse on throws error :
> [] > = json.parse(a) syntaxerror: unexpected end of input @ object.parse (native) @ repl:1:10 @ replserver.defaulteval (repl.js:132:27) @ bound (domain.js:254:14) @ replserver.runbound [as eval] (domain.js:267:12) @ replserver.<anonymous> (repl.js:279:12) @ replserver.emit (events.js:107:17) @ replserver.interface._online (readline.js:214:10) @ replserver.interface._line (readline.js:553:8) @ replserver.interface._ttywrite (readline.js:830:14) why cant json.parse verify argument json object , nothing in case instead of throwing error?
from ecma docs on json.parse, looks first thing parse method stringify first argument using tostring(). can check docs here: http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.2.
in other words, json.parse([]) equivalent json.parse([].tostring()), equivalent json.parse(""). looking @ way, error unexpected end of input makes more sense. there's nothing parse in empty string.
answering question more directly, require performance overhead json.parse infer , serialize native javascript object json (json isn't javascript). furthermore, violate single responsibility principle (srp). it's responsibility of json.parse parse strings, not objects.
Comments
Post a Comment