Aman Gupta Aman Gupta - 1 year ago 31
Javascript Question

Why JSON.parse cant detect if argument is already in JSON format

As we know

parses the stringified
, but if a variable is already
and you try to do
on that it throws an error :

> a
> a = JSON.parse(a)
SyntaxError: Unexpected end of input
at Object.parse (native)
at repl:1:10
at REPLServer.defaultEval (repl.js:132:27)
at bound (domain.js:254:14)
at REPLServer.runBound [as eval] (domain.js:267:12)
at REPLServer.<anonymous> (repl.js:279:12)
at REPLServer.emit (events.js:107:17)
at REPLServer.Interface._onLine (readline.js:214:10)
at REPLServer.Interface._line (readline.js:553:8)
at REPLServer.Interface._ttyWrite (readline.js:830:14)

Why cant
verify that argument is already a
JSON object
and do nothing in that case instead of throwing an error?


From the ECMA docs on JSON.parse, it looks like the first thing the parse method does is stringify the first argument using toString(). You can check the docs themselves here:

In other words, JSON.parse([]) is equivalent to JSON.parse([].toString()), which is equivalent to JSON.parse(""). Looking at it this way, the error unexpected end of input actually makes much more sense. There's nothing to parse in an empty string.

Answering your question more directly, it would require some performance overhead for JSON.parse to infer and serialize a native javascript object into JSON (JSON isn't javascript). Furthermore, it would violate the single responsibility principle (SRP). It's the responsibility of JSON.parse to parse strings, not objects.