[英]How to parse Array from String in JavaScript?
My curl
call looks like 我的
curl
电话看起来像
curl -v -H 'Content-Type:application/json' -d '{"instanceIds": "[i-081ec3ffa72eb338, i-0c7474fb67bb9043]", "region": "us-west-2a"}' http://localhost:3001/instances/delete
and on my expressJS
based server, the endpoint looks like 在基于
expressJS
的服务器上,端点看起来像
app.post('/instances/delete', function (req, res) {
let {region, instanceIds} = req.body;
console.log(region + "," + instanceIds);
stopInstances(region, instanceIds)
.then(function (data) {
res.send(data);
})
.catch(function (reason) {
res.status(500).send("Error in deleting instances: " + reason);
});
});
The function stopInstances
looks like 函数
stopInstances
看起来像
export let stopInstances = function (region, instanceIds) {
let params = {InstanceIds: instanceIds, DryRun: true};
console.log(params);
return ec2.stopInstances(params).promise();
};
However, the values are printed as string
但是,这些值打印为
string
InstanceIds: '[i-081ec3ffa72eb338, i-0c7474fb67bb9043]'
How can I convert this into Array
? 如何将其转换为
Array
? I tried Array.from
but that parses each character 我尝试了
Array.from
但是解析了每个字符
Array.from('[i-081ec3ffa72eb338, i-0c7474fb67bb9043]')
(40) ["[", "i", "-", "0", "8", "1", "e", "c", "3", "f", "f", "a", "7", "2", "e", "b", "3", "3", "8", ",", " ", "i", "-", "0", "c", "7", "4", "7", "4", "f", "b", "6", "7", "b", "b", "9", "0", "4", "3", "]"]
But I want [i-081ec3ffa72eb338, i-0c7474fb67bb9043]
但我想要
[i-081ec3ffa72eb338, i-0c7474fb67bb9043]
Thanks 谢谢
My curl
call was wrong, based on comment from georg
, I fixed it to 我
curl
电话是错的基础上,从评论georg
,我把它固定
curl -v -H 'Content-Type:application/json' -d '{"instanceIds": ["i-081ec3ffa72eb338", "i-0c7474fb67bb9043"], "region": "us-west-2a"}' http://localhost:3001/instances/delete
and that fixed it. 并解决了它。
You could split the string by comma 您可以用逗号分隔字符串
var parts = your_string.split(",")
Then clean the parts, Ie Remove the braces 然后清洁零件,即拆下支架
var cleaned = parts.map( function (part) {
return part.replace(/[]/g, "");
});
That cleaned variable should now have the parts you want. 现在,已清除的变量应具有所需的部分。
Untested, and written from mobile, so you'll probably want to refactor the approach. 未经测试,并且是通过移动设备编写的,因此您可能需要重构该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.