John Paul
John Paul

Reputation: 5

Spliting string into array

How do I split the string 'data' into an array in javascript? JSON.parse gives an error

let data = "[{'index': '0', 'id': 't0', 'content': 'Hello World'}, {'index': '1', 'id': 'l1', 'content': 'Data'}, {'index': '2', 'id': 'i2', 'content': 'abc'}]";

Upvotes: 0

Views: 64

Answers (2)

Jee Mok
Jee Mok

Reputation: 6566

Your data is an invalid JSON that's why JSON.parse throws you an error.

You can paste the string here at https://jsonformatter.curiousconcept.com/ and it will tell you whats wrong with your JSON string

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371193

Replace the single-quotes with double-quotes so that it's in valid JSON format, and then JSON.parse it:

const data = "[{'index': '0', 'id': 't0', 'content': 'Hello World'}, {'index': '1', 'id': 'l1', 'content': 'Data'}, {'index': '2', 'id': 'i2', 'content': 'abc'}]";
const dataArr = JSON.parse(data.replace(/'/g, '"'));
console.log(dataArr);

(or, if at all possible, simply fix your data string so that it uses double-quotes to begin with)

Upvotes: 2

Related Questions