python-shell icon indicating copy to clipboard operation
python-shell copied to clipboard

Uncaught error when parsing JSON

Open DieterDePaepe opened this issue 9 years ago • 4 comments

I'm calling a python script that outputs JSON if everything goes right, but outputs an error message otherwise. When using {mode: 'json'}, a JSON parsing error is thrown instead of being returned through the callback.

SyntaxError: Unexpected token o
    at Object.parse (native)
    at asJson (...\node_modules\python-shell\index.js:142:21)
    at ...\node_modules\python-shell\index.js:232:35
    at Array.forEach (native)
    at PythonShell.receive (...\node_modules\python-shell\index.js:231:11)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:153:18)
    at Socket.Readable.push (_stream_readable.js:111:10)
    at Pipe.onread (net.js:531:20)

DieterDePaepe avatar Apr 29 '16 09:04 DieterDePaepe

It means non-JSON content got written to stdout, which python-shell tried to parse as JSON. In JSON mode, all output should be JSON-encoded, with carriage returns for separating messages.

extrabacon avatar Apr 29 '16 11:04 extrabacon

Yes, I know the cause. But the fact that the program didn't output JSON should be seen as an error in my opinion.

DieterDePaepe avatar Apr 30 '16 09:04 DieterDePaepe

Right, it should be handled better. I'll keep that in mind for a future version.

extrabacon avatar May 01 '16 14:05 extrabacon

I had this issue which was slowing down my development and figured out that I could use stderrParser to transform the errors to valid JSON. By doing this I got the errors come out as messages and can be caught using the pyshell.on('message', ...) and pyshell.end(...) callbacks.

Workaround:

  const options = {
    mode: 'json',
    stderrParser: (line) => JSON.stringify(line),
  };

This works for now, but it seems strange that this is needed. Shouldn't python-shell do this internally? As it is now it feels like using mode: 'json' is broken.

zoeesilcock avatar Oct 11 '19 12:10 zoeesilcock