admin管理员组

文章数量:1386709

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?

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?

Share Improve this question asked Apr 10, 2017 at 23:43 threxxthrexx 1,2352 gold badges32 silver badges61 bronze badges 1
  • 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 Commented Apr 10, 2017 at 23:49
Add a ment  | 

1 Answer 1

Reset to default 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

本文标签: javascriptConvert json object to formData (HTML5 Object)Stack Overflow