Sending Object Arrays as JSON using FormData

345 Views Asked by At

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

There are 2 best solutions below

0
Phil On BEST ANSWER

Digging into the PHP SDK code, it seems you're supposed to send the fields as plain old JSON and definitely not double-encoded

const formattedForApi = JSON.stringify({
  fields: {
    phone: [
      {
        type: "main",
        value: "313-555-2121",
      },
    ],
  },
});

fetch(`/item/app/${app_id}/`, {
  method: "POST",
  body: formattedForApi,
  headers: {
    authorization: `OAuth2 ${token}`,
    "content-type": "application/json",
  },
});
1
Dheeraj Dwivedi On

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:

const formData = new FormData();
const array = [1, 2, 3];

// Encode the array into a string
const encodedArray = JSON.stringify(array);

// Add the encoded array to the FormData object
formData.append("array", encodedArray);

// Send the FormData object in an HTTP request
fetch("https://example.com/api", {
    method: "POST",
    body: formData
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

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.