I am sending a FormData object to an endpoint. A phone number needs to be formatted as this JSON:
"phone": [{"type":"main", "value":"#"}, ...]
or it gets rejected. A single object with a two-pair of keys and values in an array.
const doStuff = () => {
const formData = new FormData()
**Have tried below for setting key/value of phone object**
// Attempt 1
formData.set('phone', [{ type: 'main', value: '313-555-2121' }])
// Returns:
"phone":"[Object Object]"
// Attempt 2
formData.set(
'phone',
JSON.stringify([{ type: 'main', value: '313-555-2121' }])
)
// Returns
"phone":"[{"type":"main","value":"313-555-2121"}]"
// Format as single "fields" object and stringify (results in fields: {...stuff}), API needs this.
const formattedForApi = JSON.stringify({fields: Object.fromEntries(formData.entries())})
// MAKE POST REQUEST...
}
The API errors on both of my attempts above. Complaining of an invalid first value which needs to be "main". Am I missing something with how stringify is affecting the data that is actually being sent?
For those wondering, the API is Podio
2
Answers
Sending arrays as JSON in FormData is possible, but it requires encoding the arrays into strings before adding them to the FormData object. Here’s an example in JavaScript:
On the server-side, you can decode the string back into an array and use it as needed. The specific implementation will depend on the server-side language you’re using.
Digging into the PHP SDK code, it seems you’re supposed to send the fields as plain old JSON and definitely not double-encoded