将由数组toString()组成的字符串转换回Array

时间:2019-05-30 15:55:39

标签: javascript typescript

我将数组转换为字符串,并将其添加到TextArea。用户编辑了TextArea,现在我需要通过调用与我最初生成的数据相同的字符串来更新数组。你会怎么做?

我产生并需要转换回数组的字符串是:

{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30} 

我尝试使用JSON解析器JSON.parse(text)

3 个答案:

答案 0 :(得分:1)

设置字符串格式:

const text = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}'

console.log(JSON.parse(`[ ${text}]`))

答案 1 :(得分:1)

您只需要将字符串格式化为JSON格式的数组即可。您可以这样做:

JSON.parse('[' + text + ']')

答案 2 :(得分:1)

下面的代码应该可以工作:

var text_string = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}';
console.log(JSON.parse(`[${text_string}]`));