简体   繁体   English

如何在dynamodb中插入json

[英]How to insert json in dynamodb

Here's my code.这是我的代码。
I want to insert asset_data json into asset_data column.我想将asset_data json 插入asset_data列。 i am using aws sdk.我正在使用 aws sdk。 It says aws sdk now has support for json.它说 aws sdk 现在支持 json。 http://aws.amazon.com/releasenotes/SDK/JavaScript/1691866671551861 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
  });

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.文档客户端通过抽象出属性值的概念来简化对 Amazon DynamoDB 中项目的处理。 This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types.此抽象对作为输入参数提供的原生 JavaScript 类型进行注释,并将带注释的响应数据转换为原生 JavaScript 类型。

For your case specifically look at the Map Attribute value (M) being passed as MapAttribute in the example below extracted from the official documentation.对于您的情况,请特别查看下面从官方文档中提取的示例中作为MapAttribute传递的 Map Attribute 值(M) 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 ):文档客户端 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);
});

DynamoDB can store JSON data , also the data format you wish to insert. DynamoDB 可以存储 JSON 数据,也可以存储您希望插入的数据格式。 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.有两种方法可用于在插入 DynamoDB 时格式化数据以及将 DB 数据检索到所需的 JSON 方法中。 https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html These methods are : input and output . https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html这些方法是: inputoutput

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" : "anandujjwal13@gmail.com", }, 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 !!乐于帮助 !! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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