Search code examples
javascriptnode.jsread-eval-print-loop

nodejs REPL doesn't process JSON.parse()?


I'm trying node with REPL, parsing from string failed like this:

$node
> var str="{'a':1,'b':2}"
undefined
> var js=JSON.parse(str)
SyntaxError: Unexpected token ' in JSON at position 1

But the reversed parse seems OK:

> var json = {a : ' 1 ',b : ' 2'};
undefined
> var str = JSON.stringify(json);
undefined
> str
'{"a":" 1 ","b":" 2"}'

Where did I get wrong?


Solution

  • You have syntax error in your JSON:

    {'a':1,'b':2}
     ^
     |
     '--- invalid syntax. Illegal character (')
    

    JSON is not the same thing as Javascript object literals. JSON is a file/data format which is compatible with object literal syntax but is more strict. The JSON format was specified by Douglas Crockford and documented at http://json.org/

    Some of the differences between JSON and object literals:

    • Property names are strings
    • Strings start and end with double quotes (")
    • Hexadecimals numbers (eg. 0x1234) are not supported

    etc.