I have done AJAX validation and validated message is returned as a JSON array. Therefore I need to check whether the keys, like name
and email
, are in that JSON array.
{ "name": { "isEmpty": "Value is required and can't be empty" }, "email": { "isEmpty": "Value is required and can't be empty" } }
Only if the key name is present, I need to write an error message to the name
field.
Following is the code to display an error if fields is entered
if (obj['name']'isEmpty'] != "") { $('#name').after(c1 + "<label class='error'>" + obj['name']['isEmpty'] + "</label>"); } if (obj['email']['isEmpty'] != "" ) { $('#email').after(c4 + "<label class='error'>" + obj['email']['isEmpty'] + "</label>"); }
But if the name
field is entered, it will not be in JSON array. So the checking statement
if (obj['name']['isEmpty'] != "")
will result in the following error:
obj.name not found
It is not necessary to have key name
in the array. At same time I need to check for this to display the error if the array possesses the key name
.
Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We’re going to discuss few methods. hasOwnProperty() This method returns a boolean denoting whether the object has the defined property as its own property (as opposed to inheriting it). Syntax: obj.hasOwnProperty(prop) Parameters:
How to check if a certain key or value exists in JSON data using jq? How to check if a certain key or value exists in JSON data using jq? You can use jq in-built function has () and contains () to check if a certain key or value exists in your JSON data.
But if the name field is entered, it will not be in JSON array. So the checking statement It is not necessary to have key name in the array. At same time I need to check for this to display the error if the array possesses the key name. if (json_object.hasOwnProperty ('name')) { //do necessary stuff }
some () is a JavaScript method that tests a callback function on all the elements of the calling array and returns true if the callback function returns true for any of them. Again, just like with the object, we could also make use of a similar customized reusable function to check a value's existence in an array:
Use JavaScript's hasOwnProperty()
function:
if (json_object.hasOwnProperty('name')) { //do struff }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With