21
votes

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?

3
If others come looking for the python/boto version of this problem, here's the relevant question: stackoverflow.com/questions/36558646/… - villasv

3 Answers

32
votes

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.

6
votes

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' }
}
-2
votes

Another approach that is easier to implement, and you let DynamoDB handle the conversion behind the curtain.

Annotate the field as @DynamoAttribute

...

@DynamoDBAttribute
private MyObjectClass myObject;

And the, you annotate the "MyObjectClass" with @DynamoDBDocument

@DynamoDBDocument
public class MyObjectClass {
....
}

And DynamoDB will convert and un-convert the "MyObjectClass myObject" to the JSON shape you posted.