简体   繁体   中英

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));

You should be just able to get the attribute with normal property access in JavaScript , either test.attributeName or test['attributeName'] where attributeName depends on what you want. In your example case, it would be problem .

But you should not do the JSON.stringify too early, since that'll convert the type to string and you cannot access the properties anymore (unless you parse the string back to object).

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM