Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve specific object from a getItem dynamoDB (JavaScript)?

getting an item from my aws database. 'test2' from below prints correctly as an item in my console. But I want to get a attribute/variable from it in the item, and return it as var test. How would I do that? For example if i wanted to get the attribute name 'problem' and return it?

var test;

ddb.getItem(param, function(err, data1) {
  if (err) {
    console.log("Error", err);
  } else {
      var test2 = JSON.stringify(data1);

    console.log("Get Success",  test2);
    test = JSON.stringify(data1, undefined, 1);

  }
});
speechOutput = `Ok ${test}. Thanks, I have reported this. Do you have anything else to report?`;

    callback(sessionAttributes,
         buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
like image 652
Steven Patrick Avatar asked Sep 20 '25 01:09

Steven Patrick


1 Answers

With aws-sdk you can turn an Item from a DynamoDB response into a more normal looking object using the Converter class available in the SDK:

So if data1 looks like this:

const data1 = {
  Item: {
   "AlbumTitle": {
     S: "Songs About Life"
   }, 
   "Artist": {
     S: "Acme Band"
   }, 
   "SongTitle": {
     S: "Happy Day"
    }
  }
}

Pass data1.Item into the unmarshall function like so:

const flat = AWS.DynamoDB.Converter.unmarshall(data1.Item);

And now flat will look like this:

{
  "AlbumTitle": "Songs About Life",
  "Artist": "Acme Band",
  "SongTitle": "Happy Day"
}

So you can access the properties like normal:

console.log(flat.Artist) #=> "Acme Band"
like image 108
andrhamm Avatar answered Sep 21 '25 19:09

andrhamm