July 4, 2020
How to Check if Key is Present in JSON Object in Javascript
In this tutorial, you will learn how to check if a key is present in a JSON object in javascript. By JSON object, we simply mean JSON string. It is extremely important to verify if JSON object is missing any property before we start using it blindly. Accessing any property without performing any checks can lead to unforeseen errors in production.
- We have selected two elements
button
andh1
using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have a global variable
jsonObj
and it holds a JSON object. - We have attached the
click
event listener to thebutton
element. - In the
click
event handler function, we are callingJSON.parse()
method and passing our global variablejsonObj
as a parameter. This method simply parses JSON object and returns a javascript object. We assigned returned value to theobj
variable. - We are using the
hasOwnProperty()
method to check if there is a property with a keyname
. - We are setting the inner text of the
h1
element to the Boolean value returned by thehasOwnProperty()
method.
let btnCheck = document.querySelector('button'); let result = document.querySelector('h1'); let jsonObj = '{"name":"Peter","age":"30"}'; btnCheck.addEventListener('click', () => { let obj = JSON.parse(jsonObj); result.innerText = obj.hasOwnProperty('name') ? 'True' : 'False'; });
We have also covered in the past how to validate JSON string in Javascript. We suggest you have a look over that article and include that validation code as part of your error handling mechanism.
In the following example, we have a global JSON object. We simply want to verify if this JSON object has a
name
property or not. After verification, we will display a Boolean value on the screen. Please have a look over the code example and steps given below.HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.button
element is“Check”
and for theh1
element is“Result”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript