Home > Software engineering >  How to convert 'string of array objects' to an array in react?
How to convert 'string of array objects' to an array in react?

Time:11-08

I have researched a few questions on StackOverflow but couldn't find a relevant answer.

I have a string of array like this:

"[{"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"}}]"

and I need to convert it to an array as shown below:

Desired Output Image

I tried JSON.parse() but it didn't work!

CodePudding user response:

It is because of the \n in your JSON. Here an explanation: https://stackoverflow.com/a/5191059/11749096

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

CodePudding user response:

You have not a string of array, the first and the last double quote must be one quote in your case because when you stringify an array it works like this :

const goo = [{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

to stringify it :

JSON.stringify(goo)
'[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]'
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

in this case your parse works like :

JSON.parse(foo)
0: {insert: 'Test'}
1: {insert: '\n', attributes: {…}}
length: 2
[[Prototype]]: Array(0)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related