Reputation: 133
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) {
}
})
}
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);
}
Upvotes: 0
Views: 8352
Reputation: 5297
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;
}
check if Json string has value in JS
Upvotes: 3
Reputation: 4233
Just try to parse it using JSON.parse
, if the parse was successful return true else return false:
function isJSON(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Upvotes: 2