Skip to content
Advertisement

What would be the T-SQL equivalent of the Oracle JSON_EQUAL Condition?

  • I have a table with a column that contains a JSON string.
  • I need to query that table to find rows that match a given input JSON string.
  • I would like to ignore order and formatting.
    • ‘{ “foo”: “bar” }’ should equal ‘{“foo”:”bar”}’
    • ‘{ “foo”: “bar”, “a”: “b” }’ should equal ‘{ “a”: “b”, “foo”: “bar” }’
  • I want to avoid explicitly testing individual values as the level of nesting or number of properties may change over time.

I’m not familiar with Oracle but I have seen reference to its JSON_EQUAL condition which seems to do exactly what I need. I haven’t been able to find anything similar in T-SQL. I’ve tried using JSON_QUERY to compare the entire objects but it seems to basically just do a string comparison so variations in order and whitespace are treated as differences.

e.g. the sample below will return the [AreEqual] value as 0

Is there a way to achieve this through T-SQL?

Advertisement

Answer

There is no direct equivalent to JSON_EQUAL so I think you will have to roll your own. There is a useful example here and I started to work up an example. OPENJSON allows you to convert JSON to a table format without specifying individual field names.

I would say this is just an example that has been lightly tested on just a couple of samples, more as a proof-of-concept. It is not a production ready piece of code and needs to be thoroughly tested. That said, it might provide you a way of comparing JSON:

I was able to do some further testing based on the original JSON_EQUAL script and got the same results. See this gist for the full script.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement