如何检查JSON字符串在JavaScript中是否具有值?

Bal*_*an웃 5 javascript

有没有办法检查json字符串是否具有值(char或string)?这是一个例子:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": 10021
    }
}
Run Code Online (Sandbox Code Playgroud)

我要检查这个json是否有"m".它必须知道"m"存在于一个值中.

Moa*_*han 9

使用此方法,如果你有json字符串,你可以使用json = $.parseJSON(jsonStr)解析 -

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;
}
Run Code Online (Sandbox Code Playgroud)


djh*_*eru 5

假设将JSON对象分配给var user

if(JSON.stringify(user).indexOf('m') > -1){  }
Run Code Online (Sandbox Code Playgroud)

对不起,在阅读新评论后,我发现你只是想查看字符串是否仅在密钥中.我以为你在寻找整个JSON中的'm'(作为一个字符串)