简体   繁体   中英

Converting string to object using JSON.parse

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.

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 eg 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))

your problem is, '':'' is not json. You have to use.

import json
json.dump(<data>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM