简体   繁体   中英

Appending JSON array object to formdata

I have a JSON array object called contacts:

var contacts = [];

After some processing the value of contacts look like:

[{ "Country":"country 1", "Phone":"123" },{ "Country":"country 2", "Phone":"456" }]

Now I want to add this to the "Contacts" name inside the formdata. For that I use:

var formdata = new FormData();
formdata.append("Contacts", JSON.stringify(contacts));

When I try alert(JSON.stringify(formdata)); on button click I get:

\"Contacts\":\"[{\\\"Country\\\":\\\"country 1\\\",\\\"Phone\\\":\\\"123\\\"},
{\\\"Country\\\":\\\"country 2\\\",\\\"Phone\\\":\\\"456\\\"}]\"}"

The problem is that in the API, its not detecting the list of contacts. I tried using POSTMAN as:

Contacts[0].Country : country 1
Contacts[0].Phone : 123
Contacts[1].Country : country 2
Contacts[1].Phone : 456

API accepts data in that case. API accepts rest of the formdata fields except this, just sharing this info to rule out issue with api.

API accepts a collection of contacts as well as other fields like Name, Age and then Contacts.

If your API accepts your data in that format, you cannot send it as JSON, you need to create a separate FormData entry for each of the lines you've mentioned.

For example

const contacts = [{ "Country":"country 1", "Phone":"123" },{ "Country":"country 2", "Phone":"456" }];


var formdata = new FormData();

// This could be made fancier but it explains how to fix the problem
for (let i=0; i < contacts.length; i++) {
   formdata.append(`Contacts[${i}].Country`, contacts[i].Country);
   formdata.append(`Contacts[${i}].Phone`, contacts[i].Phone);
}

Note that json-form-data does it for you

 const data = { Contacts: [{ "Country": "country 1", "Phone": "123" }, { "Country": "country 2", "Phone": "456" }] }; const formData = jsonToFormData(data); for (const [key,value] of formData.entries()) { console.log(`${key}: ${value}`); }
 <script src="https://unpkg.com/json-form-data@^1.7.0/dist/jsonToFormData.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM