Atharva Jawalkar
Atharva Jawalkar

Reputation: 186

How to get value of key from jsondata

{
"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

Upvotes: 0

Views: 185

Answers (4)

James
James

Reputation: 698

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);
}

Upvotes: 1

Subhash Singh Negi
Subhash Singh Negi

Reputation: 46

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.

Upvotes: 1

Sumesh TG
Sumesh TG

Reputation: 2575

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.

Upvotes: 2

Abdullah Danyal
Abdullah Danyal

Reputation: 1146

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

data.Records[0].body

Upvotes: 2

Related Questions