【问题标题】:Nodejs unable to extract JSON valuesNodejs 无法提取 JSON 值
【发布时间】:2021-12-16 04:51:00
【问题描述】:

变量 SNS 是一个 JSON 对象。我想从中提取值并将其存储在另一个变量中。

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

我想从SNS JSON 变量中提取Trigger.NamespaceTrigger.Dimensions.valueTrigger.MetricName

   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)  

我收到以下错误:

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:

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

【问题讨论】:

    标签: javascript node.js json aws-lambda amazon-sns


    【解决方案1】:

    您应该将 JSON 解析成这样的对象:

    const snsObj = JSON.parse(sns);
    

    然后尝试访问该属性:

    snsObj.Trigger.Namespace
    

    【讨论】:

    • 您的答案假定 OP 尝试访问数据时数据存在。
    • 是的,数据确实存在。它的 cloudwatch 数据事件。
    • 好答案。这里的挑战是sns 变量实际上包含一个表示对象而不是对象本身的 JSON 字符串,but console.log 以相似(但不相同)的方式打印两者,从而导致混淆。
    • SO that would have helped solve this problem 上已经有很多答案了。
    【解决方案2】:

    使用您的 console.log(sns) 值进行测试时没有问题。

    我可以查看事件数据吗?

    【讨论】:

    • 我希望这是因为这是评论而不是答案。
    • 哦,以后我会小心的。
    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多