0

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'}]";
1
  • 5
    JSON uses double quotes (not single). Your JSON is invalid. Commented Jul 14, 2018 at 7:19

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.