Uploading JSON Object using s3.putObject uploads key but not the value

1.6k Views Asked by At

I am crafting a simple json object and uploading it to digital ocean using the s3.putObject function. There are no problems getting it to upload but when I look at it on digital ocean, only the key is there in the json object, and the value shows {}

Here is the code creating the JSON, and uploading it:

async function sendErrorData(error){
  var errorfile = {
    'errorLog' : error
  }
  console.log(errorfile)

  const params = {
    Body: JSON.stringify(errorfile),
    Bucket: 'MyBucket'
    Key: 'errors.json',
    ContentType: "application/json"
  };

  await uploadToDO(params)
  .then((data) => console.log(JSON.stringify(data)))
  .catch((err) => console.log(JSON.stringify(err)))

  console.log(errorfile)
}

function uploadToDO(params) {
  return s3.putObject(params).promise()
}

The console logs before and after the upload show the object perfectly fine, but once uploaded it's missing the values like this.

{
    "errorLog": ReferenceError: ....
}

Uploaded:

{
    "errorLog": {}
}
2

There are 2 best solutions below

2
On
{
    "errorLog": ReferenceError: ....
}

Is invalid JSON by the looks of things. You ask AWS to upload as application/json file and it is not so fails.

Therefore when you construct the errorfile

var errorfile = {
    'errorLog' : JSON.stringify(error)
  }

Note: This will save the error possibly as a string and not as a JSON object. If you need it as a JSON object you'd need to construct it yourself.

2
On

You are awaiting on the function call uploadToDO(params). But the function uploadToDO is not defined as an async function.

it should be:

async function uploadToDO(params) {
  return s3.putObject(params).promise()
}

Hope this helps.