querystring.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // based on the qs module, but handles null objects as expected
  2. // fixes by Tomas Pollak.
  3. var toString = Object.prototype.toString;
  4. function stringify(obj, prefix) {
  5. if (prefix && (obj === null || typeof obj == 'undefined')) {
  6. return prefix + '=';
  7. } else if (toString.call(obj) == '[object Array]') {
  8. return stringifyArray(obj, prefix);
  9. } else if (toString.call(obj) == '[object Object]') {
  10. return stringifyObject(obj, prefix);
  11. } else if (toString.call(obj) == '[object Date]') {
  12. return obj.toISOString();
  13. } else if (prefix) { // string inside array or hash
  14. return prefix + '=' + encodeURIComponent(String(obj));
  15. } else if (String(obj).indexOf('=') !== -1) { // string with equal sign
  16. return String(obj);
  17. } else {
  18. throw new TypeError('Cannot build a querystring out of: ' + obj);
  19. }
  20. };
  21. function stringifyArray(arr, prefix) {
  22. var ret = [];
  23. for (var i = 0, len = arr.length; i < len; i++) {
  24. if (prefix)
  25. ret.push(stringify(arr[i], prefix + '[]'));
  26. else
  27. ret.push(stringify(arr[i]));
  28. }
  29. return ret.join('&');
  30. }
  31. function stringifyObject(obj, prefix) {
  32. var ret = [];
  33. Object.keys(obj).forEach(function(key) {
  34. ret.push(stringify(obj[key], prefix
  35. ? prefix + '[' + encodeURIComponent(key) + ']'
  36. : encodeURIComponent(key)));
  37. })
  38. return ret.join('&');
  39. }
  40. exports.build = stringify;