Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshall DynamoDB JSON

Given some DynamoDB JSON via a DynamoDB NewImage stream event, how do I unmarshall it to regular JSON?

{"updated_at":{"N":"146548182"},"uuid":{"S":"foo"},"status":{"S":"new"}}

Normally I would use AWS.DynamoDB.DocumentClient, however I can't seem to find a generic Marshall/Unmarshall function.

Sidenote: Do I lose anything unmarshalling DynamoDB JSON to JSON and back again?

like image 930
hendry Avatar asked Jun 14 '17 04:06

hendry


People also ask

Does DynamoDB support JSON?

The latest Amazon DynamoDB update added support for JSON data, making it easy to store JSON documents in a DynamoDB table while preserving their complex and possibly nested shape.

What is Marshall in DynamoDB?

marshall(data, options) ⇒ map Convert a JavaScript object into a DynamoDB record. Examples: Convert a JavaScript object into a DynamoDB record.

Does DynamoDB return JSON?

The AWS SDKs use JSON to send data to DynamoDB, and DynamoDB responds with JSON.


2 Answers

You can use the AWS.DynamoDB.Converter.unmarshall function. Calling the following will return { updated_at: 146548182, uuid: 'foo', status: 'new' }:

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

Everything that can be modeled in DynamoDB's marshalled JSON format can be safely translated to and from JS objects.

like image 183
giaour Avatar answered Sep 19 '22 14:09

giaour


AWS SDK for JavaScript version 3 (V3) provides nice methods for marshalling and unmarshalling DynamoDB records reliably.

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);

Output:

// 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' }
}
like image 35
burntsugar Avatar answered Sep 18 '22 14:09

burntsugar