从DynamoDB响应中删除数据类型描述符的推荐方法是什么?

时间:2018-07-22 00:00:21

标签: javascript amazon-web-services aws-lambda amazon-dynamodb

DynamoDB包含查询响应中每个元素的数据类型描述符,如下所示:

"Item": { 
    "M" : {
        "Age": {"N": "8"},
        "Name": {"S": "Fido"},
        "Vaccinations": {
            "M": {
                "Rabies": {
                    "L": [
                        {"S": "2009-03-17"},
                        {"S": "2011-09-21"},
                        {"S": "2014-07-08"}
                    ]
                },
                "Distemper": {"S": "2015-10-13"}
            }
        }
    }
}

我想剥离所有这些描述符(“ S”,“ L”,“ M”等),以便在我JSON.stringify数据之前,看起来像下一个示例。

"Item": {
    "Age": "8",
    "Name": "Fido",
    "Vaccinations": {
        "Rabies": [
            "2009-03-17",
            "2011-09-21",
            "2014-07-08"
         ]
         "Distemper": "2015-10-13"
     }
}

执行此操作是否有标准(或推荐)方法?

6 个答案:

答案 0 :(得分:2)

也许是这样的:

var data= {"Item": {
    "Age": {"N": "8"},
    "Name": {"S": "Fido"},
    "Vaccinations": {
        "M": {
            "Rabies": {
                "L": [
                    {"S": "2009-03-17"},
                    {"S": "2011-09-21"},
                    {"S": "2014-07-08"}
                ]
            },
            "Distemper": {"S": "2015-10-13"}
        }
}}};

var keys_black_list=['N', 'S', 'M', 'L'];

function correct_data(_data){
  var new_data={};
  for(var key in _data){
	   if (typeof _data[key] === 'object') {
	   	   for(var bl_key in keys_black_list){
	   	   	  if(_data[key][keys_black_list[bl_key]]){

	   	   	  	 if(typeof _data[key][keys_black_list[bl_key]] === 'object'){
	   	   	  	 	new_data[key]=correct_data(_data[key][keys_black_list[bl_key]]);
	   	   	  	 }else{
	   	   	  	 	new_data[key]=_data[key][keys_black_list[bl_key]];
	   	   	  	 }
	   	   	  }
	   	   }
	   }
  }
  return new_data;
}


console.log(correct_data(data.Item));

答案 1 :(得分:2)

他们有一个可以使用的转换器。

例如,这是他们的示例:

var data= {"Item": {
    "Age": {"N": "8"},
    "Name": {"S": "Fido"},
    "Vaccinations": {
        "M": {
            "Rabies": {
                "L": [
                    {"S": "2009-03-17"},
                    {"S": "2011-09-21"},
                    {"S": "2014-07-08"}
                ]
            },
            "Distemper": {"S": "2015-10-13"}
        }
}}};
var marshalled = AWS.DynamoDB.Converter.unmarshall(data);

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/Converter.html

答案 2 :(得分:1)

不熟悉使用DynamoDb。我的猜测是有SDK可以用来为您完成此操作,或者可以使用查询中的设置来关闭描述符

以下内容似乎适用于您样本中的所有情况

var descriptors = ['L', 'M', 'N', 'S'];

function flatten(o) {

  // flattens single property objects that have descriptors  
  for (let d of descriptors) {
    if (o.hasOwnProperty(d)) {
      return o[d];
    }
  }

  Object.keys(o).forEach((k) => {

    for (let d of descriptors) {
      if (o[k].hasOwnProperty(d)) {
        o[k] = o[k][d];
      }
    }
    if (Array.isArray(o[k])) {
      o[k] = o[k].map(e => flatten(e))
    } else if (typeof o[k] === 'object') {
      o[k] = flatten(o[k])
    }
  });

  return o;
}

data = flatten(data)
console.log(data)
.as-console-wrapper {
  max-height: 100%;
}
<script>
  var data = {"Item":{"Age":{"N":"8"},"Name":{"S":"Fido"},"Vaccinations":{"M":{"Rabies":{"L":[{"S":"2009-03-17"},{"S":"2011-09-21"},{"S":"2014-07-08"}]},"Distemper":{"S":"2015-10-13"}}}}};
</script>

答案 3 :(得分:1)

答案 4 :(得分:1)

sdk 版本 3 有编组和解组实用程序

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_util_dynamodb.html

import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';

try {
  const data = await ddbClient.send(new GetItemCommand(configReadService.params));
  return unmarshall(data.Item) as unknown as ConfigAssets;
} catch (e) {
  console.log('Reading the configuration database failed ', e)
}

答案 5 :(得分:-1)

通过使用@bwinant建议的DynamoDB DocumentClient,可以完全避免类型描述符。

下面的示例在http请求处理程序中使用docClient get()和put():

// handleHttpRequest is the entry point for Lambda requests
exports.handleHttpRequest = function(request, context, done) {
  try {
    const id = request.pathParameters.id;
    let response = {
      headers: {},
      body: '',
      statusCode: 200
    };

    switch (request.httpMethod) {
      case 'GET': {
        let dynamo = new AWS.DynamoDB();
        var params = {
          TableName: myTable,
          Key: { 'id' : id },
        };

        docClient.get(params, function(err, data) {
          if (err) {
            throw `Dynamo Get Error (${err})`
          } else {
            response.body = JSON.stringify(data.Item);
            done(null, response);          
          }
        });
        break;
      }

      case 'POST': {
        let myData = JSON.parse(request.body || '{}');
        let params = {
          TableName: myTable,
          Item: {
            id : id,
            my_data : myData
          }
        }
        docClient.put(params, function(err, data) {
          if (err) {
            throw `Dynamo Put Error (${err})`;
          } else {
            done(null, data);
          }
        });
      }
    }
  } catch (e) {
    done(e, null);
  }
}