如何在dynamodb中插入json

How to insert json in dynamodb

这是我的代码。
我想将 asset_data json 插入 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
  });

您可以使用 DynamoDB 文档客户端 SDK:

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.

对于您的情况,请特别查看从官方文档中提取的以下示例中作为 MapAttribute 传递的地图属性值 (M)。 Document Client API 负责 Javascript 和 DynamoDB 类型之间的正确 marshalling/unmarshalling(这意味着您不必指定 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 可以存储 JSON 数据,也是您希望插入的数据格式。 有两种方法可用于在插入 DynamoDB 时格式化数据,以及在将 DB 数据检索到所需的 JSON 方法时。 https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html 这些方法是:inputoutput.

为此,我分享了两个 AWS lambda 代码示例片段,希望这能解决您的问题。

通过以下方式,您可以将 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;
};

通过以下方式,您可以将 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;
};

对我有用。 乐于帮助 !! :)