[英]How to retrieve specific object from a getItem dynamoDB (JavaScript)?
getting an item from my aws database. 从我的AWS数据库中获取项目。 'test2' from below prints correctly as an item in my console.
下面的“ test2”作为控制台中的一项正确打印。 But I want to get a attribute/variable from it in the item, and return it as var test.
但是我想从项目中获取属性/变量,并将其作为var测试返回。 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. 您应该只能够通过JavaScript在
test.attributeName
或test['attributeName']
中获得具有常规属性访问权限 test['attributeName']
其中attributeName取决于您想要的内容。 In your example case, it would be problem
. 在您的示例情况下,这将是
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). 但是您不应该过早地执行
JSON.stringify
,因为那样会将类型转换为字符串,并且您将无法再访问属性(除非您将字符串解析回对象)。
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: 使用aws-sdk,您可以使用SDK中提供的Converter类将DynamoDB响应中的项目变成外观更普通的对象:
So if data1
looks like this: 因此,如果
data1
看起来像这样:
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: 像这样将
data1.Item
传递到unmarshall
函数中:
const flat = AWS.DynamoDB.Converter.unmarshall(data1.Item);
And now flat
will look like this: 现在,
flat
将如下所示:
{
"AlbumTitle": "Songs About Life",
"Artist": "Acme Band",
"SongTitle": "Happy Day"
}
So you can access the properties like normal: 因此,您可以像普通方式一样访问属性:
console.log(flat.Artist) #=> "Acme Band"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.