0

I need to convert from a FormData object to the same format that bodyparser converts to in node to use in a websocket message. I'm using feathersjs to generate API services which support both REST and websocket clients.

I haven't been able to find a solution that supports field groupings or as node bodyparser calls it - "extended: true" mode. This includes inputs that are arrays:

// Singular value
<input type='text' name='test' value='1'/>

// [] creates an array
<input type='text' name='jobs[]' value='234'/>
<input type='text' name='jobs[]' value='532'/>

// Arrays are kept arrays if numeric keys and handle nested arrays
<input type='text' name='student[0][name]' value='joe'/>
<input type='text' name='student[0][food]' value='pizza'/>
<input type='text' name='student[1][name]' value='cleo'/>
<input type='text' name='student[1][food]' value='kibble'/>

// Sparse arrays stay arrays
<input type='text' name='car[]' value='240zx'/>
<input type='text' name='car[3]' value='F150'/>

// Non numeric arrays are converted to objects
<input type='text' name='multi[]' value='1'/>
<input type='text' name='multi[test]' value='1'/>
<input type='text' name='multi[3]' value='1'/>

When submitting this as a post to a NodeJS server it comes across as this object:

{
  "test": "1",
  "jobs": [
    "1",
    "2"
  ],
  "student": [
    {
      "name": "joe",
      "food": "pizza"
    },
    {
      "name": "cleo",
      "food": "kibble"
    }
  ],
  "car": [
    "240zx",
    "F150"
  ],
  "multi": {
    "0": "1",
    "3": "1",
    "test": "1"
  }
}

One thing to note is when all keys are numeric, it parses as an array. If the array is sparse it changes it to be sequential. If alphanumeric keys are used, it parses as an object. Checkboxes are weird as arrays since they only have a value when on but even body parser handles them poorly so I'm not worried about that.

My project does not depend on jQuery and I don't want to add that dependency. I'm aware of the jquery serializeObject plugin that can do this but I'm looking for a no dependency solution or simple library.

Are there any newer ways of easily converting to this format? I only need to support browser versions from the past two years.

Here is a basic JS fiddle with the form and expected output:

https://jsfiddle.net/dcnvx94w/1/

Please Note

There is this stack overflow for "FormData to Object" and there's a couple answers that are close but don't really mimic bodyparsers output. With feathersjs auto creating using the same API for both REST and Websockets, the data that comes across needs to be identically formatted. This question is also originally from ~5 years ago, and the newest answer that somewhat support nested values is from 2019. Web moves fast so I'm guessing there's an elegant modern solution to this.

How to convert FormData (HTML5 object) to JSON

Joe Jankowiak
  • 809
  • 11
  • 31

0 Answers0