Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a JSON string has a value in JavaScript?

Tags:

javascript

Is there is any way to check if the json string has the value(char or string)? Here is the example:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    }
}

I have to check if this json has "m". It must know that "m" exists in a value.

like image 709
BalaKrishnan웃 Avatar asked Dec 04 '22 09:12

BalaKrishnan웃


1 Answers

use this method, if you have json string, you can use json = $.parseJSON(jsonStr) to parse -

function checkForValue(json, value) {
    for (key in json) {
        if (typeof (json[key]) === "object") {
            return checkForValue(json[key], value);
        } else if (json[key] === value) {
            return true;
        }
    }
    return false;
}
like image 143
Moazzam Khan Avatar answered Dec 06 '22 23:12

Moazzam Khan