解组DynamoDB JSON

hen*_*dry 7 json amazon-web-services aws-sdk-js

通过DynamoDB NewImage流事件给出一些DynamoDB JSON,如何将其解组为常规JSON

{"updated_at":{"N":"146548182"},"uuid":{"S":"foo"},"status":{"S":"new"}}
Run Code Online (Sandbox Code Playgroud)

通常我会使用AWS.DynamoDB.DocumentClient,但我似乎无法找到通用的Marshall/Unmarshall函数.

旁注:我是否会丢失任何将DynamoDB JSON为JSON并再次返回的内容?

gia*_*our 17

你可以使用这个AWS.DynamoDB.Converter.unmarshall功能.调用以下内容将返回{ updated_at: 146548182, uuid: 'foo', status: 'new' }:

AWS.DynamoDB.Converter.unmarshall({
    "updated_at":{"N":"146548182"},
    "uuid":{"S":"foo"},
    "status":{"S":"new"}
})
Run Code Online (Sandbox Code Playgroud)

可以使用DynamoDB的编组JSON格式建模的所有内容都可以安全地转换为JS对象.

  • 我打开了一个PR,通过添加一个不需要`M`键的`marshall`函数来改进API,它包含在SDK的2.71.0版本中. (2认同)

bur*_*gar 9

AWS SDK为JavaScript第3版(V3)提供了很好的方法,编组反编组DynamoDB可靠的记录。

const { marshall, unmarshall } = require("@aws-sdk/util-dynamodb");

const dynamo_json = { "updated_at": { "N": "146548182" }, "uuid": { "S": "foo" }, "status": { "S": "new" } };

const to_regular_json = unmarshall(dynamo_json);

const back_to_dynamo_json = marshall(to_regular_json);
Run Code Online (Sandbox Code Playgroud)

输出:

// dynamo_json    
{ 
      updated_at: { N: '146548182' },
      uuid: { S: 'foo' },
      status: { S: 'new' }
}

// to_regular_json
{ updated_at: 146548182, uuid: 'foo', status: 'new' }

// back_to_dynamo_json
{
   updated_at: { N: '146548182' },
   uuid: { S: 'foo' },
   status: { S: 'new' }
}
Run Code Online (Sandbox Code Playgroud)

  • 哇!你不知道这有多难找到。我没有看到太多的文档,或者我在 DynamoDB 文档中是盲目的,这似乎是使用它时必须拥有的工具! (6认同)
  • 为了在 TypeScript 中实现这一点,我必须将 unmarshall(recordImage as { [key: string]: AttributeValue }); 转换为 unmarshall(recordImage as { [key: string]: AttributeValue }); // AttributeValue = import { AttributeValue } from "@aws-sdk/client-dynamodb"; (3认同)