Reputation: 311
I am having issues converting a string to an object.
I have this code run on page load
router.get('/dashboard', ensureAuthenticated, (req, res) => {
var dataToSend2;
// spawn new child process to call the python script
const ls = spawn('python', ['./readDirectory.py']);
// collect data from script
ls.stdout.on('data', function (data) {
console.log('Pipe data from python script ...');
dataToSend2 = data.toString();
console.log(JSON.parse(dataToSend2));
});
// in close event we are sure that stream from child process is closed
ls.on('close', (code) => {
console.log(`child process close all stdio with code ${code}`);
// send data to browser
})
res.render('dashboard', {
directory: dataToSend2
})
This ^ runs this python script
import os
for root, dirs, files in os.walk(".", topdown=True):
items = {
'root': root, 'label': dirs, 'files': files
}
print(items)
This then gives me this output (snippit of the output)
{'root': '.\\node_modules\\acorn\\bin', 'label': [], 'files': ['acorn', 'generate-identifier-regex.js', 'update_authors.sh']} {'root': '.\\node_modules\\acorn\\dist', 'label': [], 'files': ['.keep', 'acorn.es.js', 'acorn.js', 'acorn_loose.es.js', 'acorn_loose.js', 'walk.es.js', 'walk.js']} {'root': '.\\node_modules\\acorn\\rollup', 'label': [], 'files': ['config.bin.js', 'config.loose.js', 'config.main.js', 'config.walk.js']}
But when I try and run this I get an error saying
{'root': '.', 'label': ['config', 'models', 'node_modules', 'public', 'routes', 'views'], 'files': ['app.js', 'bundle.js', 'package-lock.json', 'package.json', 'readDirectory.py', 'readFile.py', 'README.md']}
^
SyntaxError: Unexpected token ' in JSON at position 1
What could I be doing wrong? I am trying to convert this to an object to iterate through later. I tried doing this without converting the information from the data pipeline to a string, but then I just get a bunch of buffer information sent to the browser.
Upvotes: 0
Views: 67
Reputation: 750
your problem is, '':'' is not json. You have to use.
import json
json.dump(<data>)
Upvotes: 0
Reputation: 1914
You must return valid json
, not python, though it's in this case almost the same, except the missing double quotes. Also, I think you should join all the results e.g. in a list:
import os
import json
items = []
for root, dirs, files in os.walk(".", topdown=True):
items.append({'root': root, 'label': dirs, 'files': files})
print(json.dumps(items))
Upvotes: 4