Search code examples
javascriptnode.jsjsonaws-lambdaamazon-sns

Nodejs unable to extract JSON values


Variable SNS is a JSON object. And I want to extract values from it and store it inside another variable.

  `const sns = event.Records[0].Sns.Message;`

I want to extract Trigger.Namespace and Trigger.Dimensions.value and Trigger.MetricName from the SNS JSON variable.

   const sns_NameSpace = sns.Trigger.Namespace;
   const sns_ApiId = sns.Trigger.Dimensions.value;
   const sns_MetricName = sns.Trigger.MetricName;
   console.log(sns_ApiId + '_' + sns_MetricName)
   console.log(sns_NameSpace)  

I get the following error:

ERROR   Invoke Error    
{
    "errorType": "TypeError",
    "errorMessage": "Cannot read property 'Namespace' of undefined",
    "stack": [
        "TypeError: Cannot read property 'Namespace' of undefined",
        "    at Runtime.exports.handler (/var/task/index.js:7:38)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]

console.log(sns) returns the following:

{
    "AlarmName": "ZabbixPy 5XX Error - HTTP",
    "AlarmDescription": null,
    "AWSAccountId": "123456789",
    "NewStateValue": "ALARM",
    "NewStateReason": "Threshold Crossed: 1 out of the last 1 datapoints [24.0 (01/11/21 11:42:00)] was greater than or equal to the threshold (1.0) (minimum 1 datapoint for OK -> ALARM transition).",
    "StateChangeTime": "2021-11-01T11:43:35.422+0000",
    "Region": "Asia Pacific (Mumbai)",
    "AlarmArn": "arn:aws:cloudwatch:ap-south-1:1234567890:alarm:ZabbixPy 5XX Error - HTTP",
    "OldStateValue": "INSUFFICIENT_DATA",
    "Trigger": {
        "MetricName": "5xx",
        "Namespace": "AWS/ApiGateway",
        "StatisticType": "Statistic",
        "Statistic": "SUM",
        "Unit": null,
        "Dimensions": [
            {
                "value": "someid",
                "name": "ApiId"
            }
        ],
        "Period": 60,
        "EvaluationPeriods": 1,
        "ComparisonOperator": "GreaterThanOrEqualToThreshold",
        "Threshold": 1,
        "TreatMissingData": "- TreatMissingData:                    missing",
        "EvaluateLowSampleCountPercentile": ""
    }
}

Event data when trying to filter out:

enter image description here

Event data without any filters - console.log(sns):

enter image description here


Solution

  • You should parse the JSON into an object like this:

    const snsObj = JSON.parse(sns);
    

    and then try to access the property:

    snsObj.Trigger.Namespace