最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert json object to formData (HTML5 Object) - Stack Overflow

programmeradmin3浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论