【问题标题】:Formatting DynamoDB data to normal JSON in Typescript and AWS Lambda在 Typescript 和 AWS Lambda 中将 DynamoDB 数据格式化为普通 JSON
【发布时间】:2022-01-20 13:42:25
【问题描述】:

我正在使用查询从 DynamoDB 检索数据,并返回以下内容:

[{"serviceUserId":{"S":"123456789"},"createdDate":{"S":"11-12-2021"}}]

DynamoDB JSON 格式具有我试图通过转换为普通 JSON 格式来摆脱的类型。我曾尝试使用AWS.DynamoDB.Converter.unmarshall,但我的代码出现错误:

Argument of type 'ItemList' is not assignable to parameter of type "AttributeMap".
  Index signature for type 'string' is missing in type "AttributeMap[]".

这是我的代码:

                 if (result.Count > 0) {
                     const newImage = AWS.DynamoDB.Converter.unmarshall(
                        result.Items
                         )
                   console.log('new Image: ' + JSON.stringify(newImage));
                    resolve(newImage);
                 } else { 
                     console.log('No record found');
                     reject(err);
                 }

如果我删除 DynamoDB JSON 中的 [] 括号,则它会成功转换,但显然我不能在我的程序中执行此操作,因为括号存在是有原因的!

有人知道如何将我的 JSON 文件转换为unmarshall 可以接受的格式吗?

【问题讨论】:

  • result 的值是多少? result.Items 是什么?
  • result 和 result.items 是 '[object Object]' ,当我将它字符串化时,我得到 '[{"serviceUserId":{"S":"123456789"},"createdDate":{" S":"11-12-2021"}}]'

标签: amazon-web-services amazon-dynamodb unmarshalling


【解决方案1】:

通过项目映射并一一解组。 (un)marshalaccepts an object type,不是数组。

import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';  // SDK V3, but worked the same in V2

(() => {
  const items = [{ serviceUserId: { S: '123456789' }, createdDate: { S: '11-12-2021' } }];
  
  // from DynamoDB JSON
  const unmarshalled = items.map((i) => unmarshall(i));

  // make the return trip back to DynamoDB JSON
  const marshalled = unmarshalled.map((i) => marshall(i));
})();

【讨论】:

  • 谢谢 - 我稍后会测试一下,但这一切似乎都有道理,所以希望它会起作用!
  • 不幸的是,这并不完全有效,因为我的 items 变量有字符串:'[{"serviceUserId":{"S":"123456789"},"createdDate":{"S":" 11-12-2021"}}]' 而你的是一个对象:'const items = [{ serviceUserId: { S: '123456789' }, createdDate: { S: '11-12-2021' } }];' Unmarshall 不接受字符串。
  • 此外,DynamoDB 数据可能返回多个项目:'[{"serviceUserId":{"S":"123456789"},"createdDate":{"S":"11-12 -2021"}},{"serviceUserId":{"S":"123456790"},"createdDate":{"S":"11-12-2021"},{"serviceUserId":{"S":" 123456791"},"createdDate":{"S":"11-12-2021"}}]'
  • 有什么办法解决这个问题吗?
  • 使用 JSON.parse 将您的字符串转换为 JSON。但是,如果字符串不是正确的 JSON,解析将失败。您的评论中的多个项目字符串将不会解析,因为第二个元素缺少右括号。答案将处理一系列项目。这就是map 所做的。
猜你喜欢
  • 1970-01-01
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多