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

How to create a Json File in memory from javascript object? - Stack Overflow

programmeradmin1浏览0评论

I have a backend endpoint that only accepts a json file. The user is supposed to upload a Json file and then the application submits this file to the endpoint and it works fine. Now I would like to use the same endpoint to upload json files created by the code, I would like for example to take the following javascript object

{
    name: 'Brian',
    age: 40
}

and transform it into a File object, so that I can submit it as a file, not as an object. I have tried to use the File Api constructor like this:

    new File([{ name: 'Brian', age: 40 }], "file.json", { type: "application/json" });

but the endpoint does not accept it, I assume the first argument is not in the right format... should it be a blob instead?

I have a backend endpoint that only accepts a json file. The user is supposed to upload a Json file and then the application submits this file to the endpoint and it works fine. Now I would like to use the same endpoint to upload json files created by the code, I would like for example to take the following javascript object

{
    name: 'Brian',
    age: 40
}

and transform it into a File object, so that I can submit it as a file, not as an object. I have tried to use the File Api constructor like this:

    new File([{ name: 'Brian', age: 40 }], "file.json", { type: "application/json" });

but the endpoint does not accept it, I assume the first argument is not in the right format... should it be a blob instead?

Share Improve this question asked Aug 25, 2020 at 13:22 Akira KotsugaiAkira Kotsugai 1,1593 gold badges14 silver badges25 bronze badges 1
  • what is the error that you get? – Manit Commented Aug 25, 2020 at 13:24
Add a ment  | 

1 Answer 1

Reset to default 10
const jsn = JSON.stringify(YOUR_OBJECT);
const blob = new Blob([jsn], { type: 'application/json' });
const file = new File([ blob ], 'file.json');
发布评论

评论列表(0)

  1. 暂无评论