You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.7 KiB

8 years ago
  1. // Load modules
  2. var Utils = require('./utils');
  3. // Declare internals
  4. var internals = {
  5. delimiter: '&',
  6. indices: true
  7. };
  8. internals.stringify = function (obj, prefix, options) {
  9. if (Utils.isBuffer(obj)) {
  10. obj = obj.toString();
  11. }
  12. else if (obj instanceof Date) {
  13. obj = obj.toISOString();
  14. }
  15. else if (obj === null) {
  16. obj = '';
  17. }
  18. if (typeof obj === 'string' ||
  19. typeof obj === 'number' ||
  20. typeof obj === 'boolean') {
  21. return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)];
  22. }
  23. var values = [];
  24. if (typeof obj === 'undefined') {
  25. return values;
  26. }
  27. var objKeys = Object.keys(obj);
  28. for (var i = 0, il = objKeys.length; i < il; ++i) {
  29. var key = objKeys[i];
  30. if (!options.indices &&
  31. Array.isArray(obj)) {
  32. values = values.concat(internals.stringify(obj[key], prefix, options));
  33. }
  34. else {
  35. values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']', options));
  36. }
  37. }
  38. return values;
  39. };
  40. module.exports = function (obj, options) {
  41. options = options || {};
  42. var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
  43. options.indices = typeof options.indices === 'boolean' ? options.indices : internals.indices;
  44. var keys = [];
  45. if (typeof obj !== 'object' ||
  46. obj === null) {
  47. return '';
  48. }
  49. var objKeys = Object.keys(obj);
  50. for (var i = 0, il = objKeys.length; i < il; ++i) {
  51. var key = objKeys[i];
  52. keys = keys.concat(internals.stringify(obj[key], key, options));
  53. }
  54. return keys.join(delimiter);
  55. };