Check If Json Object Contains Specific Value

Use Javascript to check if JSON object contain value

you can also use Array.some() function:

const arr = [
{
id: 19,
cost: 400,
name: 'Arkansas',
height: 198,
weight: 35
},
{
id: 21,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
},
{
id: 38,
cost: 450,
name: 'Gollum',
height: 147,
weight: 22
}
];

console.log(arr.some(item => item.name === 'Blofeld'));
console.log(arr.some(item => item.name === 'Blofeld2'));

// search for object using lodash
const objToFind1 = {
id: 21,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
};
const objToFind2 = {
id: 211,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
};
console.log(arr.some(item => _.isEqual(item, objToFind1)));
console.log(arr.some(item => _.isEqual(item, objToFind2)));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

check if json object contains specific value

Try this with for loops.

  private List<String> findScales(List<String> keys_array){
List<String> foundedScales = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(loadJSONFromAsset());
JSONArray rootElement = jsonObj.getJSONArray("allScalesJson");
ArrayList<String> scales_found = new ArrayList<>();

for (int i = 0; i < rootElement.length(); i++) {
JSONObject obj = rootElement.getJSONObject(i);

String scale = obj.getString("scale");

// Keys is json array
JSONArray genreArray = obj.getJSONArray("keys");
boolean all_found = true;

for(String key: keys_array){
boolean found_this_key = false;
for (int j = 0; j < genreArray.length(); j++) {
if(key.equals(genreArray.getString(j))){
found_this_key = true;
break;
}
}
if(!found_this_key){
all_found = false;
break;
}
}

if(all_found){
scales_found.add(scale);
}
}

return scales_found;
}catch (Exception e){e.printStackTrace();}


return foundedScales;
}

Check whether a value exists in JSON object

var JSON = [{"name":"cat"}, {"name":"dog"}];

The JSON variable refers to an array of object with one property called "name".
I don't know of the best way but this is what I do?

var hasMatch =false;

for (var index = 0; index < JSON.length; ++index) {

var animal = JSON[index];

if(animal.Name == "dog"){
hasMatch = true;
break;
}
}

How to check if a key exists in Json Object and get its value

Use below code to find key is exist or not in JsonObject. has("key") method is used to find keys in JsonObject.

containerObject = new JSONObject(container);
//has method
if (containerObject.has("video")) {
//get Value of video
String video = containerObject.optString("video");
}

If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject.

How to check if a value exists in a JSON Array for a particular key?

First you need to deserialize the JSON code to a JsonArray in this way:

JsonArray jsonArr = gson.fromJson(jsonString, JsonArray.class);

After that you can create this method:

public boolean hasValue(JsonArray json, String key, String value) {
for(int i = 0; i < json.size(); i++) { // iterate through the JsonArray
// first I get the 'i' JsonElement as a JsonObject, then I get the key as a string and I compare it with the value
if(json.get(i).getAsJsonObject().get(key).getAsString().equals(value)) return true;
}
return false;
}

Now you can call the method:

hasValue(jsonArr, "methodName", "addRole");

how do i see if a big JSON object contains a value?

You can use the hasOwnProperty method:

if (ents.hasOwnProperty('7')) {
//..
}

This method checks if the object contains the specified property regardless of its value.

Is faster than the in operator because it doesn't checks for inherited properties.

How to check if a JSON key exists?

JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Returns true if this object has a mapping for name. The mapping may be NULL.

How to determine if a JSON object contains only a specific key?

You can always just count the properties of a JObject using JContainer.Count. You want objects with one property, named "Name":

foreach (var category in jObject["Categories"].OfType<JObject>())
{
var result = category.Count == 1 && category.Property("Name") != null;
}

The fact that you're using dynamic makes it a little harder to access the c# properties of your category JObject, since there might also be a JSON property named "Count". I'd suggest switching to explicitly typed objects and methods instead. Doing so will also give you compile-time error checking as well as possibly improved performance, as explained in How does having a dynamic variable affect performance?.

Sample fiddle here.

Update

Should I go for the Except(...).Any() solution, what would I need to put in the parenthesis?

According to the documentation, Enumerable.Except

Produces the set difference of two sequences.

So you could try something like:

    var result = !category.Properties()
.Select(p => p.Name)
.Except(new [] { "Name" })
.Any();

However, there is a problem with this approach: using Except() does not meet your stated requirement that you need to

... determine for each category whether or not it consists of the Name key only.

Except(...).Any() will test whether there are additional keys other than Name, but it will not test for the presence of the Name key itself, since it will get filtered out. Thus an empty JSON object {} would incorrectly get accepted.

Instead, you would need to check for sequence equality, e.g. like so:

foreach (var category in jObject["Categories"].OfType<JObject>())
{
var result = category.Properties()
.Select(p => p.Name)
.SequenceEqual(new [] { "Name" });
}

And if you were requiring the presence of multiple keys, since a JSON object is an unordered set of name/value pairs according to the standard, you could sort them to require an unordered sequence equality:

var requiredKeys = new [] { "Name" } // Add additional required keys here
.OrderBy(n => n, StringComparer.Ordinal).ToArray();
foreach (var category in jObject["Categories"].OfType<JObject>())
{
var result = category.Properties()
.Select(p => p.Name)
.OrderBy(n => n, StringComparer.Ordinal)
.SequenceEqual(requiredKeys);
}

Or if you prefer you could use requiredKeys.ToHashSet(StringComparer.Ordinal) and then SetEquals().

But, in my opinion, if you just need to check whether a JSON object consists of a single specified key only, the initial solution is simplest and most declarative.

Demo fiddle #2 here.



Related Topics



Leave a reply



Submit