如何从jsondata获取密钥的值

时间:2018-10-15 14:46:13

标签: javascript node.js json lambda amazon-sqs

{
"Records": [{
    "messageId": "20ea364e-3bc107b5c78c",
    "receiptHandle": "AQEB6DhNloFS4R66c=",
    "body": "1",
    "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "15393506",
        "SenderId": "AROAJMTI6NE:errorLog",
        "ApproximateFirstReceiveTimestamp": "15393511"
    },
    "messageAttributes": {},
    "md5OfBody": "c4ca75849b",
    "eventSource": "aws:sqs",
    "eventSourceARN": "arn:aws:sqs:ap-suth-1:83362:escalateErrorStandardQueue",
    "awsRegion": "ap-south-1"
}]

}

我想获取键“ body”的值,预期输出应为:1

4 个答案:

答案 0 :(得分:2)

如果jsondata的名称为data(可以说):

data.Records[0].body

答案 1 :(得分:2)

var data={
"Records": [{
    "messageId": "20ea364e-3bc107b5c78c",
    "receiptHandle": "AQEB6DhNloFS4R66c=",
    "body": "1",
    "attributes": {
        "ApproximateReceiveCount": "1",
        "SentTimestamp": "15393506",
        "SenderId": "AROAJMTI6NE:errorLog",
        "ApproximateFirstReceiveTimestamp": "15393511"
    },
    "messageAttributes": {},
    "md5OfBody": "c4ca75849b",
    "eventSource": "aws:sqs",
    "eventSourceARN": "arn:aws:sqs:ap-suth-1:83362:escalateErrorStandardQueue",
    "awsRegion": "ap-south-1"
}]
};
console.log(data.Records[0].body);

您只需通过data.Records[0].body即可访问数据。

答案 2 :(得分:1)

尝试一下:

(data && data['Records'] && data['Records'][0] && data['Records'][0]['body']) || 1;

它永远不会给您任何错误,如果不存在则返回键'body'的值1。

答案 3 :(得分:1)

如果您的记录是数组,则可以尝试迭代Records并获取正文的值。

此外,如果您要进行布尔条件运算,则最好将值解析为整数,因为来自JSON的数据将自然返回字符串;在我的示例中,我使用+ Unary Plus运算符对其进行了解析。

var data = {
  "Records": [{
      "messageId": "20ea364e-3bc107b5c78c",
      "receiptHandle": "AQEB6DhNloFS4R66c=",
      "body": "1",
      "attributes": {
          "ApproximateReceiveCount": "1",
          "SentTimestamp": "15393506",
          "SenderId": "AROAJMTI6NE:errorLog",
          "ApproximateFirstReceiveTimestamp": "15393511"
      },
      "messageAttributes": {},
      "md5OfBody": "c4ca75849b",
      "eventSource": "aws:sqs",
      "eventSourceARN": "arn:aws:sqs:ap-suth-1:83362:escalateErrorStandardQueue",
      "awsRegion": "ap-south-1"
  }]
};

for (record in data.Records)
{
  console.log('Normal JSON value:', typeof data.Records[record].body);
  console.log('Parsed JSON value:', typeof +data.Records[record].body);
  console.log('The Record body is:', +data.Records[record].body);
}