JS, how to append array in FormData?
You need to stringify your data first:
fd.append("key", JSON.stringify(["a","b","c"]));
And then when you want to retrieve the data parse it back into an array. This can be done manually using JSON.parse()
, or, if you're using express, can be done for you by using the JSON/urlencoded body-parser middleware.
Explanation:
When you use .append()
, the data passed as a second argument will be converted into a string. In the case of an array, the .toString()
method gets called which joins the elements inside your array by a comma
a,b,c
This isn't good as this cannot be parsed back into the array easily, especially when you have complex arrays such as an array of objects or a multi-dimensional array.
However, as @Phil pointed out, you can manage this by using JSON.stringify
on your input array. This way, you're providing a JSON string, which can easily be parsed back into data using JSON.parse()
"[\"a\",\"b\",\"c\"]" // <-- can be parsed into an array using JSON.parse()
See working example below:
var fd = new FormData();
fd.append("key", JSON.stringify(["a","b","c"]));
var str_arr = fd.get("key");
console.log(str_arr); // string format
console.log(JSON.parse(str_arr)); // array format
gdk
Updated on June 04, 2022Comments
-
gdk almost 2 years
i hope append array in js FormData.
like this,
var fd = new FormData(); fd.append("key", new Array(["a","b","c"])); console.log(fd.get("key"));
the result is,
a,b,c
result type is 'String'...
i want to parse "aa" array in java(JSONArray).
please help me.
-
Phil over 5 years"the result is
a,b,c
" 👈 that's becauseFormData
only accepts string orBlob
values (see developer.mozilla.org/en-US/docs/Web/API/FormData/…) so the array is being converted to a string. It's unclear what you want the value to actually be
-
-
Phil over 5 yearsWhy not use
JSON.stringify()
on the value when appending it instead of attempting to build your own JSON formatter -
Nick Parsons over 5 years@Phil good point actually! I've updated my answer to use this instead. thanks
-
bubble-cord over 3 yearsAnyone new coming here for reference,
fd.append("key", JSON.stringify(new Array(["a","b","c"])));
can be simply eased tofd.append("key", JSON.stringify(["a","b","c"]));
. No need to addnew Array
to an existing array of items. -
Nick Parsons over 3 years@bubble-cord good point, I must’ve kept it from the OP’s question. I’ve updated it to remove the array constructor