1

I have seen many posts about converting formData to JSON object, however, I have the exact opposite use case. I have a JSON object which I would like to convert to a formData object as this is required by my endpoint API.

My code right now:

formdata = new FormData();
var uploadJson = {
  "default_lang": "en",
  "words": [
    {
      "desc": $scope.selectedWord,
      "enabled": true,
      "examples": $scope.examples
    }
  ]
};

formdata.append('file', uploadJson);

However, formdata is always empty even after appending uploadJson.

Does anyone know how to fix/do that?

threxx
  • 1,213
  • 1
  • 31
  • 59
  • FormData always runs `.toString()` on appended fields, so it runs: uploadJson.toString() which results in [object Object] (at least in my case). Can you post how you check if formdata is empty? Also ajax code maybe? – posixpascal Apr 10 '17 at 23:49

1 Answers1

4

Try stringifying the javascript object to json.

formdata.append('file', JSON.stringify(uploadJson));

Note that JSON is a string data format and there is no such thing as a JSON object

Community
  • 1
  • 1
charlietfl
  • 170,828
  • 13
  • 121
  • 150