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
1 Answer
Reset to default 10const jsn = JSON.stringify(YOUR_OBJECT);
const blob = new Blob([jsn], { type: 'application/json' });
const file = new File([ blob ], 'file.json');