Parse the JSON string with
JSON.parse
to get a JavaScript Object.Use
in
operator to check the member existencevar jsObj = JSON.parse('{"p": 5}'); console.log(jsObj); if ("p" in jsObj) { console.log("`p` exists"); }
Output
{ p: 5 } `p` exists
Best way to find whether a value exists in a JSON object in javascript?
-
27-09-2022 - |
Question
I have a single level JSON to search through for the presence of a given value. Is there is a compact method provided in ecma5 for the same ?
Solution
OTHER TIPS
Since it sounds like you're looking for a specific value in an unknown key, assuming there that you already parsed your JSON, you'll need something more like:
function valueExists(jsObj, value){
for (var key in jsObj){
if (jsObj[key] == value) return true;
}
return false;
}
Parse the JSON string with JSON.parse to get a JavaScript Object, and do
Simplest check,
if(jsonObj['key']) {
}
Working fiddle
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow