0
{
"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"
}]

}

I want to get the value of key "body" and expected output should be : 1

  • Did you tried `data.Records[0].body`? where data is the name of the variable assigned to this `json` – brk Oct 15 '18 at 14:48

4 Answers4

2

If the name of the jsondata is data (lets say):

data.Records[0].body
Abdullah Danyal
  • 866
  • 1
  • 7
  • 23
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);

You can access the data by simply data.Records[0].body.

Sumesh TG
  • 2,367
  • 1
  • 12
  • 29
1

try this:

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

it will never give you any error and return key 'body' value if exist otherwise 1.

1

If your records is an array, you could try to iterate your Records and get the value of body.

Also, if you're doing boolean conditionals, it is good practice to parse the value to an integer because data from a JSON will return string (naturally); in my example I parse it with the + Unary Plus operator.

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);
}
James
  • 659
  • 1
  • 8
  • 22