6

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?

1
  • what is the error that you get? Commented Aug 25, 2020 at 13:24

1 Answer 1

10
const jsn = JSON.stringify(YOUR_OBJECT);
const blob = new Blob([jsn], { type: 'application/json' });
const file = new File([ blob ], 'file.json');
Sign up to request clarification or add additional context in comments.

2 Comments

a verbal explanation is often helpful
I believe you can also do const file = new File([ JSON.stringify(YOUR_OBJECT) ], 'file.json', { type: 'application/json' });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.