Is there any easy way to check if one JsonDocument has the same elements as another JsonDocument? I want to achieve something like b.Except(a).Any()
for List.
Edit:
What I want is not DeepEquals as it compares absolutely everything and if there is the slightest mismatch it will give me false.
It will be a bit of c#-like pseudocode but consider this scenario:
b = {
"prop1": 1,
"prop2": "apple"
}
a = {
"prop1": 1,
"prop2": "apple",
"prop3": "extra big"
}
I wan behavoiour like !b.Except(a).Any()
because it would give me true
in above scenario. DeepEquals
will get me false.
2
Answers
To achieve the behavior you’re looking for, where one JSON document (b) is a subset of another JSON document (a), you can iterate through the properties of both JsonDocument objects and compare them in a non-strict manner. You could use the following approach in C#:
Parse both JSON documents into JsonElement objects.
Loop through the properties of b and check if each property exists in a with the same value.
If all properties in b exist in a and match, return true; otherwise, return false.
Here’s an example:
gecapo’s answer almost got it right, but not quite:
The problem is that
superProp
andproperty.Value
are bothJsonElement
objects, and that struct neither implementsIEquatable
nor does it override theEquals
method (see JsonElement.cs source code).Therefore
superProp.Equals(property.Value)
is basically a call toValueType.Equals
, which returnsfalse
(maybe becauseJsonElement
has an internal reference to_parent
, I don’t know).JsonElement
does have aValueEquals()
method, but it only works for properties withJsonValueKind.String
.The only way I could find would be to use
GetRawText()
and make a string comparison. I inserted a check of theValueKind
property though, because why bother retrieving string values of arbitrary length when a simple enum comparison could detect mismatches already.I’ve also converted the method to an extension and named it slightly differently, because I think
docB.IsSubsetOf(docA)
is much clearer thanIsSubset(docB, docA)
.https://dotnetfiddle.net/I2AxoN