将本地文本文件转换为javascript中的对象作为用户配置文件
我试图创建一个“保存文件”,这样用户就可以下载配置并将其加载到站点中。 以下是我试图实现的目标: config.txt将本地文本文件转换为javascript中的对象作为用户配置文件,javascript,regex,javascript-objects,Javascript,Regex,Javascript Objects,我试图创建一个“保存文件”,这样用户就可以下载配置并将其加载到站点中。 以下是我试图实现的目标: config.txt projectName: 'Lorem', timeStarted: '12:21:00', tasks: [ 'Do this', 'Do that', 'Then this', 'Then that' ] js对象 projectName: 'Lorem', timeStarted: '12:21:00', tasks: [ 'Do this', 'Do that', '
projectName: 'Lorem',
timeStarted: '12:21:00',
tasks: [
'Do this',
'Do that',
'Then this',
'Then that'
]
js对象
projectName: 'Lorem',
timeStarted: '12:21:00',
tasks: [
'Do this',
'Do that',
'Then this',
'Then that'
]
我尝试过使用split、map和reduce的方法,但仍然无法将文本转换为对象
这是我的密码:
let str = [config.txt];
let output = str.split("\n")
.map(a => a.match(/(.*): '(.*)',/))
.reduce([haven't figured out this part]);
我希望对象内部有一个数组。我通过使用JSON找到了解决方案,如下所示
//to set the object
var config = {
"projectName": "Lorem",
"timeStarted": "12:21:00",
"tasks": [
"Do this",
"Do that",
"Then this",
"Then that" ]
}
// to convert the object into string
var asString = JSON.stringify(config);
// to process and parse the string back to object
var asObject = JSON.parse(asString);
我以前无法使用JSON.parse,因为我将config对象作为参数。为什么不直接使用?顺便说一下,您问题中的数据结构无效。您发布的js对象无效;看起来tasks属性应该是数组而不是数组object@Dario@str my bad,是的,我希望任务是数组。我如何实际使用JSON生成包含数组的对象?