Skip to content

Instantly share code, notes, and snippets.

@dsdstudio
Last active August 29, 2015 14:22
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 dsdstudio/87f180b501b6aecf1dcd to your computer and use it in GitHub Desktop.
Save dsdstudio/87f180b501b6aecf1dcd to your computer and use it in GitHub Desktop.
complex data structure json to form data
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
@dsdstudio
Copy link
Author

앜.. angularjs 와 의존성이 있다..
의존성 제거 필요..

@dsdstudio
Copy link
Author

angularjs 의존성 제거

@dsdstudio
Copy link
Author

TODO Array.isArray polyfill 작성해야함

@dsdstudio
Copy link
Author

깊은 depth일때 배열 순회후 attribute가 최상위 node 에 붙는 문제 수정

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment