I have an array of objects like this.
var arr = [
{name: 'myName', age: 25, city: 'myCity'},
{name: 'myName1', age: 25, city: 'myCity1'}
];
Now, I need to pass this arr array into a payload as a JSON object.
I used JSON.stringify(arr) and then passed the data. But it is getting converted into a form-data and the payload format is like below;
[{name: 'myName', age: 25, city: 'myCity'},{name: 'myName1', age: 25, city: 'myCity1'}]:
If you have noticed a colon at the end of the payload, seems like it converted my array as a property name to the form data. Can you help me to pass the array as a JSON object.
Code that is used to call the API method is,
{
type: 'POST',
method: 'POST',
dataType: 'json',
url: 'url of the api call',
beforeSend: function(header, settingsData){
Object.keys(settingsData.options).forEach(headerKey){
headerKey.setHeader(headerKey, settingsData.options[headerKey]);
}
return settingsData;
},
disableDefaultError: true
}
CodePudding user response:
- Keep
dataType: 'json' - add
contentType: 'application/json'since the default is'application/x-www-form-urlencoded; charset=UTF-8'
{
type: 'POST',
method: 'POST',
dataType: 'json',
contentType: 'application/json', // <- this is needed
url: 'url of the api call',
beforeSend: function(header, settingsData){
Object.keys(settingsData.options).forEach(headerKey){
headerKey.setHeader(headerKey, settingsData.options[headerKey]);
}
return settingsData;
},
disableDefaultError: true
}
