formDataToJSON.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. 'use strict';
  2. import utils from '../utils.js';
  3. import AxiosError from '../core/AxiosError.js';
  4. import { DEFAULT_FORM_DATA_MAX_DEPTH } from './toFormData.js';
  5. const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
  6. function throwIfDepthExceeded(index) {
  7. if (index > MAX_DEPTH) {
  8. throw new AxiosError(
  9. 'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
  10. AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
  11. );
  12. }
  13. }
  14. /**
  15. * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
  16. *
  17. * @param {string} name - The name of the property to get.
  18. *
  19. * @returns An array of strings.
  20. */
  21. function parsePropPath(name) {
  22. // foo[x][y][z] -> ['foo', 'x', 'y', 'z']
  23. // foo.x.y.z -> ['foo', 'x', 'y', 'z']
  24. // A path is split on `.` and on `[...]` groups. A segment — whether written
  25. // in dot notation or captured inside brackets — may contain any character
  26. // except `.`, `[` and `]`, so a key like `user-name` or `user name` is kept
  27. // literal instead of being split (#5402). `.`, `[` and `]` keep their existing
  28. // meaning, e.g. `foo[bar.baz]` -> ['foo', 'bar', 'baz'] and `[]` is an array push.
  29. // Excluding `[` from the bracket group also makes the match fail fast at the
  30. // next `[`, so a malformed name cannot rescan to the end of the string from
  31. // every unmatched `[` — parsing stays linear in the length of the name.
  32. const path = [];
  33. const pattern = /[^.[\]]+|\[([^.[\]]*)]/g;
  34. let match;
  35. while ((match = pattern.exec(name)) !== null) {
  36. throwIfDepthExceeded(path.length);
  37. path.push(match[0] === '[]' ? '' : match[1] || match[0]);
  38. }
  39. return path;
  40. }
  41. /**
  42. * Convert an array to an object.
  43. *
  44. * @param {Array<any>} arr - The array to convert to an object.
  45. *
  46. * @returns An object with the same keys and values as the array.
  47. */
  48. function arrayToObject(arr) {
  49. const obj = {};
  50. const keys = Object.keys(arr);
  51. let i;
  52. const len = keys.length;
  53. let key;
  54. for (i = 0; i < len; i++) {
  55. key = keys[i];
  56. obj[key] = arr[key];
  57. }
  58. return obj;
  59. }
  60. /**
  61. * It takes a FormData object and returns a JavaScript object
  62. *
  63. * @param {string} formData The FormData object to convert to JSON.
  64. *
  65. * @returns {Object<string, any> | null} The converted object.
  66. */
  67. function formDataToJSON(formData) {
  68. function buildPath(path, value, target, index) {
  69. throwIfDepthExceeded(index);
  70. let name = path[index++];
  71. if (name === '__proto__') return true;
  72. const isNumericKey = Number.isFinite(+name);
  73. const isLast = index >= path.length;
  74. name = !name && utils.isArray(target) ? target.length : name;
  75. if (isLast) {
  76. if (utils.hasOwnProp(target, name)) {
  77. target[name] = utils.isArray(target[name])
  78. ? target[name].concat(value)
  79. : [target[name], value];
  80. } else {
  81. target[name] = value;
  82. }
  83. return !isNumericKey;
  84. }
  85. if (!utils.hasOwnProp(target, name) || !utils.isObject(target[name])) {
  86. target[name] = [];
  87. }
  88. const result = buildPath(path, value, target[name], index);
  89. if (result && utils.isArray(target[name])) {
  90. target[name] = arrayToObject(target[name]);
  91. }
  92. return !isNumericKey;
  93. }
  94. if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
  95. const obj = {};
  96. utils.forEachEntry(formData, (name, value) => {
  97. buildPath(parsePropPath(name), value, obj, 0);
  98. });
  99. return obj;
  100. }
  101. return null;
  102. }
  103. export default formDataToJSON;