Parse urlencoded string into JSON in ONE line of code
The source code can be found in: https://github.com/shlomisderot/url-encoded
I would like to share with you some regex practice that I had to deal with...
From security aspects the internet transform every message to urlencoded,
I look for some Node libraries to do that, but those that I found was quite messy and contains too much lines of code or they didn't do the job so, I decide to do it by myself, surprisingly, I replaced all the "libraries" into one line of code thanks to regular expression...
the motivation is to convert urlencoded string ('application/x-www-form-urlencoded') into valid JSON string in order to use JSON.parse function.
I got the following string:
'protocol=echo-protocol&topic=assets%3Aremove&data=%7B%22uid%22%3A%22bd17ecad-fc2e-4568-ae21-ad08ddf48b59%22%2C%22gid%22%3A%221a71d70d-bc5b-46f1-b6ec-16776b6285eb%22%2C%22data%22%3A%7B%22id%22%3A%225c1116adc9c31f74efcdafbe%22%7D%7D'
And I needed to convert it to valid JSON, something like:
{
data: {
product_id: "5c1116adc9c31f74efcdb022",
group_id: "1a71d70d-bc5b-46f1-b6ec-16776b6285eb",
user_id: "bd17ecad-fc2e-4568-ae21-ad08ddf48b59"
},
protocol: "echo-protocol",
topic: "assets:remove"
}
The solution:
JSON.parse(decodeURIComponent('url encoded string').replace(/=([^&]+)\&/g, "=\"$1\",\n\r").replace(/(^|\r)([^=]+)=/g, "\"$2\":").replace(/^/, '{').replace(/$/, '}'))
Explanation:
- use javascript decodeURIComponent function in order to decode the urlencoded string.
- .replace(/=([^&]+)\&/g, "=\"$1\",\n\r") - replace all ampersands, with line feed and carriage return, notice that I'm using global (g) regexp modifier.
- .replace(/(^|\r)([^=]+)=/g, "\"$2\":") - take all words after starting line (^) or carriage return (\r) until the equal sign and put it inside quotation marks and add colons (:) right after, again, notice that I'm using global (g) regexp modifier.
- .replace(/^/, '{') - replace the starting string (^) with open curly brackets.
- .replace(/$/, '}') - replace the end of string ($) with close curly brackets.
- run JSON.parse on the result
Nice, but doesn't work for Forms with collections :(
Looks pretty cool and useful, thank you for the one-liner, and thanks for the regex explanation as well. :)