[英]Converting string to object using JSON.parse
I am having issues converting a string to an object.我在将字符串转换为 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这 ^ 运行这个 python 脚本
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)然后这给了我这个 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.
我正在尝试将其转换为 object 以便稍后进行迭代。 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.您必须返回有效的
json
,而不是 python,尽管在本例中它几乎相同,只是缺少双引号。 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.您的问题是,'':'' 不是 json。您必须使用。
import json
json.dump(<data>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.