threxx
threxx

Reputation: 1235

Convert json object to formData (HTML5 Object)

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?

Upvotes: 1

Views: 10143

Answers (1)

charlietfl
charlietfl

Reputation: 171700

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

Upvotes: 4

Related Questions