[英]cannot convert string in array format such as “[55]” to array
I receive the following from another server in my payload as query param: 我从有效负载中的另一台服务器收到以下内容作为查询参数:
"[55]"
Now I want to convert it to an array in JavaScript, 现在,我想将其转换为JavaScript中的数组,
Here is what I do: 这是我的工作:
var termssValidation= JSON.parse(JSON.stringify(event.termsQuery));
But when I run the following: 但是当我运行以下命令时:
for(var t in termssValidation ){
console.log(termssValidation[t]);
}
I get 3 lines as follows: 我得到3行,如下所示:
[
5
5
]
How can I convert the above to an array properly? 如何将以上内容正确转换为数组?
您只需要解析JSON字符串。
console.log(JSON.parse('[55]'));
JSON.stringify
is excess JSON.stringify
是多余的
let j = JSON.parse("[55]") console.log(j)
The problem is the inner JSON.stringify(). 问题是内部JSON.stringify()。 This method converts the "[66]" into ""[66]"".
此方法将“ [66]”转换为““ [66]””。 JSON.parse then converts this string as if the inner quotes were escaped.
然后,JSON.parse将转换此字符串,就好像转义了内部引号一样。 So the result is the original string "[66]".
因此,结果是原始字符串“ [66]”。 Because the String in javascript is an iterable you get the individual characters as the result of the iteration.
由于javascript中的String是可迭代的,因此您将获得单个字符作为迭代的结果。
This is the solution to your problem: 这是您的问题的解决方案:
var termssValidation= JSON.parse(event.termsQuery);
This code works! 此代码有效!
let a = "[55]"; a = JSON.parse(a); for (let i in a) { console.log(a[i]); //55 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.