如何在反应中将 'string of array objects' 转换为数组?
How to convert 'string of array objects' to an array in react?
我在 Whosebug 上研究了几个问题,但找不到相关答案。
我有一个 数组字符串 像这样:
"[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}},{"insert":"Asdasfff"},{"insert":"\n","attributes":{"list":"bullet"}},{"insert":"Asadsf"},{"insert":"\n","attributes":{"list":"bullet"}},{"insert":"Sfsfsft"},{"insert":"\n","attributes":{"header":2}},{"insert":"Make"},{"insert":"\n","attributes":{"list":"unchecked"}},{"insert":"Back"},{"insert":"\n","attributes":{"list":"checked"}},{"insert":"Ban"},{"insert":"\n","attributes":{"list":"unchecked"}},{"insert":"Fg"},{"insert":"\n","attributes":{"list":"checked"}}]"
我需要将其转换为数组,如下所示:
我试过JSON.parse()
但是没用!
是因为你的JSON中的\n
。这里有一个解释:
function jsonEscape(str) {
return str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
}
var data = `[{"insert":"Test"},{"insert":"\n","attributes": 0}]`;
var dataObj = JSON.parse(jsonEscape(data));
console.log(dataObj);
您没有数组字符串,第一个和最后一个双引号在您的情况下必须是一个引号,因为当您对数组进行字符串化时,它的工作方式如下:
const goo = [{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]
将其字符串化:
JSON.stringify(goo)
'[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]'
在这种情况下,您的解析工作方式如下:
JSON.parse(foo)
0: {insert: 'Test'}
1: {insert: '\n', attributes: {…}}
length: 2
[[Prototype]]: Array(0)
我在 Whosebug 上研究了几个问题,但找不到相关答案。
我有一个 数组字符串 像这样:
"[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}},{"insert":"Asdasfff"},{"insert":"\n","attributes":{"list":"bullet"}},{"insert":"Asadsf"},{"insert":"\n","attributes":{"list":"bullet"}},{"insert":"Sfsfsft"},{"insert":"\n","attributes":{"header":2}},{"insert":"Make"},{"insert":"\n","attributes":{"list":"unchecked"}},{"insert":"Back"},{"insert":"\n","attributes":{"list":"checked"}},{"insert":"Ban"},{"insert":"\n","attributes":{"list":"unchecked"}},{"insert":"Fg"},{"insert":"\n","attributes":{"list":"checked"}}]"
我需要将其转换为数组,如下所示:
我试过JSON.parse()
但是没用!
是因为你的JSON中的\n
。这里有一个解释:
function jsonEscape(str) {
return str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
}
var data = `[{"insert":"Test"},{"insert":"\n","attributes": 0}]`;
var dataObj = JSON.parse(jsonEscape(data));
console.log(dataObj);
您没有数组字符串,第一个和最后一个双引号在您的情况下必须是一个引号,因为当您对数组进行字符串化时,它的工作方式如下:
const goo = [{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]
将其字符串化:
JSON.stringify(goo)
'[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]'
在这种情况下,您的解析工作方式如下:
JSON.parse(foo)
0: {insert: 'Test'}
1: {insert: '\n', attributes: {…}}
length: 2
[[Prototype]]: Array(0)