1

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!

1

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

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.