I am retrieving data from DynamoDB using a query and I get the following returned:
[{"serviceUserId":{"S":"123456789"},"createdDate":{"S":"11-12-2021"}}]
The DynamoDB JSON format has the type in in which I am trying to get rid of by converting to a normal JSON format. I have tried using the AWS.DynamoDB.Converter.unmarshall
but I am getting an error in my code:
Argument of type 'ItemList' is not assignable to parameter of type "AttributeMap".
Index signature for type 'string' is missing in type "AttributeMap[]".
Here is my code:
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);
}
If I remove the [] brackets in the DynamoDB JSON then it is converted successfully, but obviously I cannot do this in my program as the brackets are there for a reason!
Does anyone know how to convert my JSON file to a format that unmarshall
will accept?
CodePudding user response:
Map through the items and unmarshal one by one. (un)marshal
accepts an object type, not an array.
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));
})();