Skip to content

Instantly share code, notes, and snippets.

@maxcnunes
Created July 3, 2014 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcnunes/18d5bb6dfcdf13e76498 to your computer and use it in GitHub Desktop.
Save maxcnunes/18d5bb6dfcdf13e76498 to your computer and use it in GitHub Desktop.
After I had completed the script `parse-nodejs-express-body-by-hand.js` I sort out was possible get the same result using the `qs` library :D
// before
{ 'content[title]': 'test',
'content[excerpt]': 'test',
'content[content]': 'test',
'content[featuredImage][title]': 'test',
'content[source][title]': 'test',
'content[source][url]': 'http://google.com',
'content[source][author]': 'test',
'content[source][publishedAt]': '25/07/2014',
'content[topics]': '539f11bcfdf15258000d9922' }
// after:
{ content:
{ title: 'test',
excerpt: 'test',
content: 'test',
featuredImage: { title: 'test' },
source:
{ title: 'test',
url: 'http://google.com',
author: 'test',
publishedAt: '25/07/2014' },
topics: '539f11bcfdf15258000d9922' } }
function parse (req, res, next) {
var body = {};
Object.getOwnPropertyNames(req.body).forEach(function(name) {
var value = req.body[name],
baseField = getBaseFieldName(name),
fields = getInnerFieldsNames(name),
obj = {},
prev,
prop;
if (!body[baseField]) body[baseField] = {};
for (var i = fields.length - 1; i >= 0; i--) {
prop = fields[i];
if (i === 0) {
obj = prev || value;
}
else if (i === fields.length - 1) {
obj[prop] = value;
prev = obj;
} else {
obj[prop] = prev;
prev = obj;
}
}
body[baseField][prop] = obj;
});
req.body = body;
next();
}
function getBaseFieldName (fieldName) {
return fieldName.match(/^([^\[]*)/)[1];
}
function getInnerFieldsNames (fieldName) {
var regex = /\[([^\]]*)\]/g;
var matches, output = [];
while (matches = regex.exec(fieldName)) {
output.push(matches[1]);
}
return output;
}
function parse (req, res, next) {
require('qs').parse(req.body);
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment