Last active
August 29, 2015 14:22
-
-
Save dsdstudio/87f180b501b6aecf1dcd to your computer and use it in GitHub Desktop.
complex data structure json to form data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function jsonToFormData($json) { | |
| function isObject($o) { return typeof $o === 'object' && $o !== null; } | |
| function isFunction($o) { return typeof $o === 'function'; } | |
| function visit($json, $arr, $prefix) { | |
| var t0, i, j; | |
| t0 = $arr || []; | |
| $prefix = $prefix || ''; | |
| for (i in $json) { | |
| if (isFunction($json[i])) continue; | |
| if ( Array.isArray($json[i]) ) { | |
| for (j in $json[i]) { | |
| if (isFunction($json[i][j])) continue; | |
| if ( isObject($json[i][j]) ) | |
| t0.concat(visit($json[i][j], t0, (($prefix ? $prefix + '.' : '') + i + '[' + j +']'))); | |
| else | |
| t0.push(($prefix ? $prefix + '.' : '') + i +'[' + j + ']' + '=' + encodeURIComponent($json[i][j])); | |
| } | |
| $prefix = $prefix || ''; | |
| continue; | |
| } | |
| if ( isObject($json[i]) ) t0.concat(visit($json[i], t0, (($prefix ? $prefix + '.' : '') + j))); | |
| else t0.push(($prefix ? $prefix + '.' : '') + i + '=' + encodeURIComponent($json[i])); | |
| } | |
| return t0; | |
| } | |
| return visit($json).join('&'); | |
| } | |
| console.log(jsonToFormData({data:[{a:1, b:2, c:3}, {a:2, b:3, c:4}], msg:'aa'})); | |
| // 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
깊은 depth일때 배열 순회후 attribute가 최상위 node 에 붙는 문제 수정