javascriptarraysjsonpodio

Sending Object Arrays as JSON using FormData


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


Solution

  • 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",
      },
    });