Anoop V
Anoop V

Reputation: 231

How to convert 'string of array objects' to an array in react?

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!

Upvotes: 1

Views: 1445

Answers (2)

Asman Takilt
Asman Takilt

Reputation: 124

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}}]

to stringify it :

JSON.stringify(goo)
'[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]'

in this case your parse works like :

JSON.parse(foo)
0: {insert: 'Test'}
1: {insert: '\n', attributes: {…}}
length: 2
[[Prototype]]: Array(0)

Upvotes: 1

SoGoddamnUgly
SoGoddamnUgly

Reputation: 766

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

Upvotes: 1

Related Questions