Advertisement
Guest User

Untitled

a guest
Jul 6th, 2015
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. function jsonToFormData($json) {
  2. function isObject($o) { return typeof $o == 'object' && $o !== null; }
  3. function visit($json, $arr, $prefix) {
  4. var t0, i, j;
  5. t0 = $arr || [];
  6. $prefix = $prefix || '';
  7. for (i in $json) {
  8. if ( typeof $json[i] == 'function' ) continue;
  9. if ( Array.isArray($json[i]) ) {
  10. for (j in $json[i]) {
  11. if ( typeof $json[i][j] == 'function' ) continue;
  12. if ( isObject($json[i][j]) )
  13. t0.concat(visit($json[i][j], t0, (($prefix ? $prefix + '.' : '') + i + '[' + j +']')));
  14. else
  15. t0.push(($prefix ? $prefix + '.' : '') + i +'[' + j + ']' + '=' + encodeURIComponent($json[i][j]));
  16. }
  17. $prefix = '';
  18. continue;
  19. }
  20. if ( isObject($json[i]) ) t0.concat(visit($json[i], t0, (($prefix ? $prefix + '.' : '') + j)));
  21. else t0.push(($prefix ? $prefix + '.' : '') + i + '=' + encodeURIComponent($json[i]));
  22. }
  23. return t0;
  24. }
  25. return visit($json).join('&');
  26. }
  27.  
  28. console.log(jsonToFormData({data:[{a:1, b:2, c:3}, {a:2, b:3, c:4}], msg:'aa'}));
  29. // data[0].a=1&data[0].b=2&data[0].c=3&data[1].a=2&data[1].b=3&data[1].c=4&msg=aa
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement