[英]Spliting string into array
How do I split the string 'data' into an array in javascript? 如何在JavaScript中将字符串“数据”拆分为数组? JSON.parse gives an error
JSON.parse给出一个错误
let data = "[{'index': '0', 'id': 't0', 'content': 'Hello World'}, {'index': '1', 'id': 'l1', 'content': 'Data'}, {'index': '2', 'id': 'i2', 'content': 'abc'}]";
Replace the single-quotes with double-quotes so that it's in valid JSON format, and then JSON.parse
it: 用双引号替换单引号,以使其具有有效的JSON格式,然后进行
JSON.parse
:
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) (或者,如果可能的话,只需修复您的
data
字符串,使其以双引号开头)
Your data
is an invalid JSON that's why JSON.parse
throws you an error. 您的
data
是无效的JSON,这就是JSON.parse
向您抛出错误的原因。
You can paste the string here at https://jsonformatter.curiousconcept.com/ and it will tell you whats wrong with your JSON string 您可以在https://jsonformatter.curiousconcept.com/上将字符串粘贴到此处,它将告诉您JSON字符串有什么问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.