Skip to content
Advertisement

How to ignore few properties in SQL Server JSON value

I have a table which has a column with JSON data. Every JSON object in each column has many properties. I have another table which has property name not all but few.

What I need to do is to write a query to select JSON data from table but JSON should not contain properties which are there in the second table. For example, below is the jSON table.

Second table with properties name:

Query should join these two table and output should be

Advertisement

Answer

This is a fully generic approach with no need for dynamic SQL:

–The query

The idea in short:

First we use a CTE to create a list of all properties within your JSON as EAV (Entity-Attribute-Value). With this its easy to get rid of all the attributes, where the name is found in your exclude table.

As we are not allowed to use a column’s value as the output column’s alias we can build the JSON with string-methods instead of a FOR JSON query.

First I use a GROUP BY to reduce the final output to one-row-per-Id, and the I use a correlated sub-query to build the JSON per Id from the corresponding EAVs.

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