-1
var  body ='{"error_type": "OAuthException", "code": 400, "error_message": "This authorization code has been used"}'
console.log(body.error_type)

I want to get value of body.error_type but is showing undefined how can I get value of it.

peterh
  • 11,875
  • 18
  • 85
  • 108

1 Answers1

1

You have enclosed the value with single quotes ('), which means that the type of body is string, not object. An object should be enclosed with curly braces ({}).

Compare the following:

const someString = '{foo: "bar"}';
const anObject = {foo: "bar"};

For your use case:

const body = {
  error_type: 'OAuthException',
  code: 400,
  error_message: 'This authorization code has been used',
};
console.log(body.error_type);

If you are receiving body from elsewhere and the value is already a string, you can parse it as an object using JSON.parse(body).

old greg
  • 799
  • 8
  • 19