[SOLVED] How to save JSON to Moralis?

In my cloud function I need to save similar JS object:

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

to a file named person.json. I want to store it on my Moralis server, not IPFS. I went through this documentation https://docs.moralis.io/moralis-server/files/files but I don’t know how to do it with JSON. Thanks :slight_smile:

you will have to convert it to string before uploading it to a file
https://docs.moralis.io/moralis-server/files/ipfs#saving-objects
this seems to work fine:

const object = {
“key” : “value”
}
const file = new Moralis.File(“file_2.json”, {base64 : btoa(JSON.stringify(object))});
await file.save();

@cryptokid thanks for this. What’s the URL of uploaded file? Is it uploaded in the main directory?

You get the url in the result of await fille.save()

1 Like

There’s one more problem - I’m getting btoa is not defined error in my cloud function. Is there a different way to convert to base64?

Working example:

const btoa = function(str){ return Buffer.from(str).toString('base64'); }

Moralis.Cloud.define("test_upload", async (request) => {
  const object = {"key" : "value"}
  const file = new Moralis.File("file_2.json", {base64 : btoa(JSON.stringify(object))});
  x = await file.save({useMasterKey:true});
  console.log(JSON.stringify(x))
  return x;            
});