0

I have a form with inputs named like so:

<input name="locations[0][name]" value="x">

I want to convert it to JSON so it looks like:

{
  "locations": [
    {
      "name": "x"
    }
  ]
}

I've tried (per this StackOverflow post):

var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);

But I end up with the key treated as a string:

{
  "locations[0][name]": "x"
}

How can I encode in JSON and use the input names to create an object/array structure? Thanks!

  • I used the solution offered in the post linked in the duplicate notice above and that worked. Thanks to whomever directed me to that! My code that worked for me: `const data = new FormData(this.$dom.form[0]); let jsonData = {}; data.forEach((value, key) => { this.$setValue(jsonData, key, value); }); jsonData = JSON.stringify(jsonData);` And `$setValue()` is the function in the linked post. – stackingjasoncooper Dec 11 '21 at 00:23

0 Answers0