检查字符串是否在json对象中 [英] Check if a string is in a json object

查看:103
本文介绍了检查字符串是否在json对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript检查字符串是否在JSON对象中。我不知道是否可能或我必须转换某些东西。下面是if语句的一部分,我想在其中检查data.userName(字符串)是否在用户中(JSON对象)

I'm trying to check if a string is in a JSON object with javascript. I don't know if it is possible or I have to convert something. Here is the part of the code with the if statement in which I want to check if data.userName (the string) is in users (the JSON object)

function validation() {
    var userName_login = document.getElementById("username").value;
    var password_login = document.getElementById("password").value;
    var data = {
        userName: userName_login,
        password: password_login
    };
    doJSONRequest("GET", "/users/", null, data, function(users) {
        if (data.userName) {

        }
    })
}

doJSONRequest函数是:

And the doJSONRequest function is:

function doJSONRequest(method, url, headers, data, callback) {
    if (arguments.length != 5) {
        throw new Error('Illegal argument count');
    }
    doRequestChecks(method, true, data);
    var r = new XMLHttpRequest();
    r.open(method, url, true);
    doRequestSetHeaders(r, method, headers);
    r.onreadystatechange = function() {
        if (r.readyState != 4 || (r.status != 200 && r.status != 201 && r.status != 204)) {
            return;
        } else {
            if (isJSON(r.responseText))
                callback(JSON.parse(r.responseText));
            else
                callback();
        }
    };
    var dataToSend = null;
    if (!("undefined" == typeof data) && !(data === null))
        dataToSend = JSON.stringify(data);
    r.send(dataToSend);
}


推荐答案

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

检查Json字符串是否在JS中有值

这篇关于检查字符串是否在json对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆