Confirming JSON Property is present

toneyvecchio1
Tera Expert

Greetings All - Hoping for some guidance. I receive JSON with some name value pairs.

{

        "A":{

                  "employeeId":"ABC",

                  "11":"DEF"

        },

        "B":{

                  "empID":"ABC",

                  "21":"OPQ"

        },

}

The payload may omit A or B entirely and so I am doing a check to see if both are present. Then I check to see if only one is present.

if(payload[A].employeeId != undefined && payload[B].empID != undefined)

However, in the case that I only get 1 - I am getting an error ""TypeError: Cannot find function getMessage in object TypeError: Cannot read property \"employeeId\" from undefined"

{

      "B":{

                  "empID":"ABC",

                  "21":"OPQ"

        },

}

What is the proper way to see if a name pair exists, as the act of checking for it seems to throw out an error?

1 ACCEPTED SOLUTION

larstange
Mega Sage

Hi



Check if the object exist before checking its properties.



if (payload[A] != undefined) {


        if(payload[A].employeeId != undefined && payload[B].empID != undefined)


}


View solution in original post

4 REPLIES 4

Jon Barnes
Kilo Sage

you need to do typeof. like this:


  1. if(typeof payload[A].employeeId != 'undefined' && typeof payload[B].empID != 'undefined')  


it should also work to do it simply like this:



if (payload.A && payload.A.employeeId && payload.B && payload.B.empID)


larstange
Mega Sage

Hi



Check if the object exist before checking its properties.



if (payload[A] != undefined) {


        if(payload[A].employeeId != undefined && payload[B].empID != undefined)


}


Shahed Shah1
Tera Guru

Not sure if this makes a difference, but are you doing this on the client side?



Also, what would happen if you do your checks like this instead:


if (payload.A.employeeId && payload.B.empID)



Whenever I've coded on the client side this is how I normally do my checks for the existence of a node.



EDIT: Just noticed Lars' update and he makes a very valid point. You should check if the parent node (e.g. A) does exist since you mention that you can get one or the other, or both


poyntzj
Kilo Sage

I'd just use JSUtil.nil or JSUtiil.notNil