Gal Appelbaum
Gal Appelbaum

Reputation: 1955

How to Verify a dynamic JSON object

I have a JSON Object that has a body part which I parse. However, The body can have a few potential outcomes based on the API ran. I can either receive in the body something like this:

body: '{"OrderNumber":"123123123","ExtraInfo":[]}'

or something like this:

body: '{"error":"Something went wrong"}' }

When I parse my object I do var temp=JSON.parse(object.body). How can I verify which type of body did I get - meaning if its body.OrderNumber or body.error ? I'd need to identify the contents of body in order to determine my next step.

Thanks for the help!

Upvotes: 1

Views: 356

Answers (3)

Djaouad
Djaouad

Reputation: 22794

function test(object) {
  var temp=JSON.parse(object.body);
  if (temp.error) {
     console.log(temp.error); // display error message
  } else {
     console.log("Success");
     console.log(temp.OrderNumber); // display result
  }
}

var object1 = {'body': '{"OrderNumber":"123123123","ExtraInfo":[]}'}
var object2 = {'body': '{"error":"Something went wrong"}'}

test(object1);
test(object2);

Upvotes: 1

sam
sam

Reputation: 246

if(body.error) {
  //logic if error is not defined 
} else {
  //your logic if there is error in body
} 

Upvotes: 0

swapnesh
swapnesh

Reputation: 26732

You can use hasOwnProperty method to check if the property is available to an object or not -

if(temp.hasOwnProperty('error') ) {
 // Show error
}
else if( temp.hasOwnProperty('OrderNumber') ) {
 // Show something
}
else {
 // Show what you want
}

Upvotes: 1

Related Questions