3000 3000 - 1 year ago 64
Javascript Question

Check for the existence of a key in a JSON coming from server

In pure JavaScript I want to check for the existence of a JSON key. The JSON is in the following form (I simplify):


I must check for the existence of "c" (
) because under some circumstances the server returns a JSON containing "d" but not "c".

I appreciate any help.

Answer Source

After you parse json with JSON.parse() you can use Object.keys() and indexOf()

var data = {"a":{"b":{"c":"","d":"t"}}}
var result = Object.keys(data.a.b).indexOf('c') != -1;

Or you can check for key with hasOwnProperty

var data = {"a":{"b":{"c":"","d":"t"}}}

if(data.a.b.hasOwnProperty('c')) console.log('True')

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download