如何将类似数组的字符串转换为Node.js中的数组?

时间:2021-01-24 22:01:59

I am writing an API in a Node.js application. This is a POST call that sends a bunch of data and along with it, it sends the timings parameter in the body as a string that looks like an array [["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]. When I am inserting it into MongoDB, it is getting stored as an array but with the entire text as a string in the first array element.

我在Node.js应用程序中编写API。这是一个发送一堆数据的POST调用,它和它一起发送正文中的timings参数作为一个看起来像数组的字符串[[“11:00 AM”,“1:00 PM”],[ “下午1:00”,“4:00 PM”]]。当我将它插入MongoDB时,它将被存储为一个数组,但整个文本作为字符串存储在第一个数组元素中。

I know I can circumvent this by asking the client application to send a comma-separated string like 11:00 AM,1:00 PM and split the string in JavaScript before inserting it into the database using String.split() but that only works for single-dimension arrays. I have a multi-dimensional array that is being sent as a string in the POST request. How do I convert it to an array?

我知道我可以通过要求客户端应用程序发送逗号分隔的字符串来解决这个问题,如上午11:00,下午1:00,并在使用String.split()将数据库插入数据库之前将其拆分为JavaScript,但这只能起作用对于单维数组。我有一个多维数组,在POST请求中作为字符串发送。如何将其转换为数组?

1 个解决方案

#1


2  

Use JSON.parse to parse string array to JS array.

使用JSON.parse将字符串数组解析为JS数组。

var timingsAr = '[["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]'
JSON.parse(timingsAr); //returns JS array

#1


2  

Use JSON.parse to parse string array to JS array.

使用JSON.parse将字符串数组解析为JS数组。

var timingsAr = '[["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]'
JSON.parse(timingsAr); //returns JS array