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.
I know I can circumvent this by asking the client application to send a ma-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?
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.
I know I can circumvent this by asking the client application to send a ma-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?
-
3
How about
JSON.parse
? – Blakes Seven Commented Sep 14, 2015 at 9:02 - 1 That worked! Thanks! Can you answer the question so I can mark it as an answer? – JackH Commented Sep 14, 2015 at 9:06
- When you assign it to a two dimensional array variable you can get the values of each value in it. does this help? - stackoverflow./questions/7545641/… – giri-sh Commented Sep 14, 2015 at 9:08
-
If you are building web servers in JavaScript then search for the term "body parser", as it is a pretty mon case to just convert string input that is acutally a
JSON
or other serialized format into a real data structure. And the work is generally handled for you. – Blakes Seven Commented Sep 14, 2015 at 9:10
1 Answer
Reset to default 6Use JSON.parse
to parse string array to JS array.
var timingsAr = '[["11:00 AM", "1:00 PM"], ["1:00 PM", "4:00 PM"]]'
JSON.parse(timingsAr); //returns JS array
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745250608a4618657.html
评论列表(0条)