node.js 如何在dynamodb中插入json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32944920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert json in dynamodb
提问by mks
Here's my code.
I want to insert asset_datajson into asset_datacolumn.
i am using aws sdk.
It says aws sdk now has support for json.
http://aws.amazon.com/releasenotes/SDK/JavaScript/1691866671551861
这是我的代码。
我想将asset_datajson插入到asset_data列中。我正在使用 aws sdk。它说 aws sdk 现在支持 json。
http://aws.amazon.com/releasenotes/SDK/JavaScript/1691866671551861
var asset_data = {
"name": "name" + i,
"contentUrl": "http://www.hdwallpapersimages.com/nature-beauty-desktop-images/94892/",
"size": 300,
"headline": "headline",
"description": "assetUrl reference for the creator",
"encodingFormat": 'jpeg'
};
var params = {
TableName: 'xyz',
Item: { // a map of attribute name to AttributeValue
"asset_id": {S: "asset" + i},
"hit_id": {S: "0"},
"created_date": {"S": Date.now().toString()},
"status": {N: "0"},
"operation": {S: "image_tagging"},
"asset_data": {L: asset_data},
"source": {S: "DAM"},
"completed_date": {S: Date.now().toString()},
"response_data": {S: "taged value"}
// more attributes...
},
ReturnValues: 'NONE', // optional (NONE | ALL_OLD)
ReturnConsumedCapacity: 'NONE', // optional (NONE | TOTAL | INDEXES)
ReturnItemCollectionMetrics: 'NONE' // optional (NONE | SIZE)
};
db.putItem(params, function (err, data) {
if (err) console.log(err); // an error occurred
else console.log("inserted..."); // successful response
});
回答by bsd
You can use the DynamoDB Document Client SDK:
您可以使用 DynamoDB 文档客户端 SDK:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property
The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types.
文档客户端通过抽象出属性值的概念来简化对 Amazon DynamoDB 中项目的处理。此抽象对作为输入参数提供的原生 JavaScript 类型进行注释,并将带注释的响应数据转换为原生 JavaScript 类型。
For your case specifically look at the Map Attribute value (M)being passed as MapAttributein the example below extracted from the official documentation. The Document Client API takes care of the proper marshalling/unmarshalling between the Javascript and DynamoDB types (meaning that you don't have to specify the Attribute Values (S,N,L,...)as it is required when using the non-document based SDK ):
对于您的情况,请特别查看从官方文档中提取的以下示例中(M)传递的 Map Attribute 值MapAttribute。文档客户端 API 负责在 Javascript 和 DynamoDB 类型之间进行正确的编组/解组(这意味着您不必Attribute Values (S,N,L,...)在使用基于非文档的 SDK 时指定所需的):
var params = {
TableName: 'Table',
Item: {
HashKey: 'haskey',
NumAttribute: 1,
BoolAttribute: true,
ListAttribute: [1, 'two', false],
MapAttribute: { foo: 'bar'},
NullAttribute: null
}
};
var docClient = new AWS.DynamoDB.DocumentClient();
docClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
回答by Anand Ujjwal
DynamoDB can store JSON data , also the data format you wish to insert.
There are two methods which can be used to format the data while inserting into DynamoDB and also while retrieving the DB data into desired JSON method.
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.htmlThese methods are : inputand output.
DynamoDB 可以存储 JSON 数据,也可以存储您希望插入的数据格式。有两种方法可用于在插入 DynamoDB 时格式化数据以及将 DB 数据检索到所需的 JSON 方法中。
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html这些方法是:input和output。
I have shared two sample snippets of AWS lambda code to do so, hope this solves your problem.
为此,我分享了两个 AWS lambda 代码示例片段,希望这能解决您的问题。
With the following way you can convert JSON data into DynamoDB supported format and then insert it:
您可以通过以下方式将 JSON 数据转换为 DynamoDB 支持的格式,然后插入:
const AWS = require('aws-sdk');
//setting the region
AWS.config.update({region: 'ap-south-1'});
// Create the DynamoDB service object
const ddb = new AWS.DynamoDB.DocumentClient();
const getParams = (updatedTasks)=>{
const params = {
TableName: 'todo-application',
Key: {
"userID" : "[email protected]",
},
UpdateExpression: "set tasks = :updatedTasks",
ExpressionAttributeValues:{
":updatedTasks":updatedTasks
},
ReturnValues:"UPDATED_NEW"
};
return params;
}
const dbQuery =(newTask)=>{
let updatedTask = AWS.DynamoDB.Converter.input(newTask, true);
console.log('updated task formatted ',updatedTask);
let params = getParams(updatedTask);
return new Promise((resolve,reject) =>{
ddb.update(params, function(err, data) {
if (err) {
console.log("Error", err);
reject(err);
} else {
console.log("Success", data);
resolve(data.Item)
}
});
});
}
exports.updateTodoJobsOfAUser = async (event) => {
const insertObject = [
{
statement:'learn Dynamo DB', id: 23
},
{
statement:'Learn Serverless Architecture',id:24
}]
const data = await dbQuery(insertObject);
const response = {
statusCode: 200,
body: JSON.stringify(data)
};
return response;
};
With following way you can convert DynamoDB data into JSON format :
通过以下方式,您可以将 DynamoDB 数据转换为 JSON 格式:
const dbQuery =()=>{
return new Promise((resolve,reject) =>{
ddb.get(params, function(err, data) {
if (err) {
console.log("Error", err);
reject(err);
} else {
console.log("Success", data);
resolve(data.Item)
}
});
});
}
exports.getAllTodoJobsOfAUser = async (event) => {
const data = await dbQuery();
const formattedData = AWS.DynamoDB.Converter.output(data, true);
const response = {
statusCode: 200,
body: JSON.stringify(formattedData)
};
return response;
};
It works for me. Happy to help !! :)
这个对我有用。乐于帮助 !!:)

