'Node.JS spawning Python process gives error 'JSONDecodeError("Expecting value", s, err.value) from None'
I'm trying to spawn a python process (App.py) from a node.js file (index.js).
The script index.js spawns the python script App.py, and passes it an argument params (a json object). App.py then reads the uParams element parameter1 and sends the value as a message back to index.js.
However when I run the index.js script I get the error, JSONDecodeError("Expecting value", s, err.value) from None.
I tried to replace json.loads(sys.argv[1]) with sys.argv[1] but running it gives me the error TypeError: string indices must be integers.
Did I wrongly format the 'params' JSON object in index.js?
Could you please help me spot the problem?
Thanks in advance!
index.js:
const spawn = require("child_process").spawn;
let params = {
"type":"numbers",
"lang":"js",
"uParams":[{
"parameter1":1,
"parameter2":2,
"parameter3":3
}]
}
const pythonProcess = spawn('python',['./App.py', params]);
pythonProcess.stdout.on('data', (data)=>{
console.log(data.toString());
});
App.py:
import sys, json
params = json.loads(sys.argv[1])
print(params['uParams'][0]['parameter1'])
sys.stdout.flush()
Solution 1:[1]
You have to stringify your JSON object with JSON.stringify.
const pythonProcess = spawn('python',['./App.py', JSON.stringify(params)]);
Frankly I'm surprised spawn isn't complaining that it only accepts string arguments, but it must be calling toString on your object so you're just passing [object Object].
> ({foo:'bar'}).toString()
'[object Object]'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | leitning |
