Reputation: 5192
I am developing restAPI using Node.js. In that the following is the URL for my API:
http://xxxxxxxx:3000/map70/places?node[level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011]
In this i have to get the each parameters level0,level1,level2,ids,key,value.
In normal url format like the below:
http://xxxxxxxx:3000/map70/places?key=xxxxxxx&val=2011&level0=2&level1=33&level2=602
I can parse like req.query.level0..
.But for the above url how can i parse it.I searched a lot,but i cant find the right solution.Help me to solve this..Thanks in advance....
Upvotes: 2
Views: 673
Reputation: 159095
Is there a name for this style of query parameter? I have never heard of it. If there's some standard around it, you might be able to find some obscure module that'll parse it. Otherwise, it's very likely you'll have to parse the string yourself.
You can get hold of the thing with Node's url
module:
var url = require('url');
var parsed = url.parse('http://xxxxxxxx:3000/map70/places?node[level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011]');
var query = parsed.query;
At this point, query
now contains node[level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011]
, and you can start to pull it apart with string operations.
[Update]
I'm only going off the URL you posted, so you'd probably need to write some tests cases to ensure all the parameters you care about get parsed, but I was able to get something like this:
var querystring = require('querystring');
var q2 = query.slice(5, -1);
// q2 == "level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011"
var q3 = q2.replace(/\]\[/g, '&');
// q3 == "level0=12&level1=34&level2=234&ids=1,2,3,4&key=xxxxxxxxxx&val=2011"
querystring.parse(q3);
// returns:
// { level0: '12',
// level1: '34',
// level2: '234',
// ids: '1,2,3,4',
// key: 'xxxxxxxxxx',
// val: '2011' }
You can combine it all together into:
querystring.parse(query.slice(5, -1).replace(/\]\[/g, '&'));
Upvotes: 2