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.
How to check for a particular key exists in json string or not
You can parse JSON string within a Script component using JavaSerializer or JSON.Net assemblies and search for the key value.
- Importing JSON Files Using SQL Server Integration Services
- newtonsoft json package requires reinstall every time i open code
If the JSON data is formal and contains only keys and values then you can search for the following string "-1":
, if it is found then the -1
key is found.
if(json.contains("\"-1\":")){
//key found
}else{
// key not found
}
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 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 JSON Array object contains a Key
myJSONArrayObject
is an array. It doesn't have 12
as a property (Unless there are 12+ items in the array)
So, check if some
of the objects in the array have myIntegerKey
as a property
const exists = data.myJSONArrayObject.some(o => myIntegerKey in o)
or if myIntegerKey
is always an own property
const exists = data.myJSONArrayObject.some(o => o.hasOwnProperty(myIntegerKey))
Here's a snippet:
const data={myJSONArrayObject:[{"12":{}},{"22":{}}]}, myIntegerKey = 12, exists = data.myJSONArrayObject.some(o => myIntegerKey in o);
console.log(exists)
How to determine if a Javascript object has only one specific key-value pair?
var keys = Object.keys(text);
var key = keys[0];
if (keys.length !== 1 || key !== "id" || text[key] !== "message")
alert("Wrong object");
how to check if a specific key exists in json object using jquery
First of all, JSON is a text-based data-interchange format, it's not an object.
To check if a key exists in an object, you can use the in
operator.
$.getJSON(sSource, aoData, function (data) {
if ('errorMessage' in data) {
//there was an error
}
});
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;
}
Related Topics
How to Use Telegram API in C# to Send a Message
Data Binding in MVC 5 and Select2 Multiple Values With Razor Engine
Encode a Filestream to Base64 With C#
How to Get the Currently Loggedin Windows Account from an ASP.NET Page
How to Cast a List into a Type Which Inherits from List<T>
How to Remove Empty Lines from a Formatted String
How to Set a Cookie on Httpclient'S Httprequestmessage
How to Submit Disabled Input in ASP.NET MVC
Multidimensional Array from a Txt File
Use Latest Version of Internet Explorer in the Webbrowser Control
How to Convert English Digits to Arabic Digits
Check If Combobox Value Is Empty
Moq - Non-Overridable Members May Not Be Used in Setup/Verification Expressions
Why Am I Getting Error Cs0246: the Type or Namespace Name Could Not Be Found
Automatically Update Values in Database from Datagridview