BalaKrishnan웃
BalaKrishnan웃

Reputation: 4557

How to check if a JSON string has a value in 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.

Upvotes: 5

Views: 34036

Answers (5)

Gibolt
Gibolt

Reputation: 47127

If looking in one layer and not a substring:

const hasValue = Object.values(obj).includes("bar");

If looking in one layer for a substring, and no objects as values:

const hasChar = Object.values(obj).join("").includes("m");

If looking in multi-layer for a substring:

const list = Object.values(a);
for (let i = 0; i < list.length; i++) {
    const object = list[i];
    if (typeof object === "object") {
        list.splice(i, 1); // Remove object from array
        list = list.concat(Object.values(object)); // Add contents to array
    }
}
// It is important to join by character not in the search substring
const hasValue = list.join("_").includes("m");

NOTE: If searching for a key instead, check this post

Upvotes: 2

Moazzam Khan
Moazzam Khan

Reputation: 3170

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;
}

Upvotes: 9

eatonphil
eatonphil

Reputation: 13682

Possibly something like this?

function parse_json(the_json, char_to_check_for)
{
    try {
        for (var key in the_json) {
            var property = the_json.hasOwnProperty(key);
            return parse_json(property);
        }
    }
    catch { // not json
        if (the_json.indexof(char_to_check_for) !=== -1)
        {
             return true;
        }
        return false;

    }
}

if (parse_json(my_json,'m'))
{
    alert("m is in my json!");
}

Upvotes: 1

tomaroo
tomaroo

Reputation: 2534

Assuming you get your object syntax corrected, you can loop through the properties in an object by using a for loop:

for(props in myObj) {
    if(myObj[props] === "m") { doSomething(); }
}

Upvotes: 1

djheru
djheru

Reputation: 3719

Assuming that the JSON object is assigned to var user

if(JSON.stringify(user).indexOf('m') > -1){  }

Sorry, upon reading new comments I see you're only looking to see if the string is in a key only. I thought you were looking for an 'm' in the entire JSON (as a string)

Upvotes: 5

Related Questions