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));
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));
Share
Improve this question
asked Mar 12, 2019 at 23:04
Steven PatrickSteven Patrick
731 gold badge2 silver badges7 bronze badges
1
- Really useful question. – Deva Commented Nov 9, 2021 at 6:38
2 Answers
Reset to default 8With 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"
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).