6

I have a table with the following schema in a SQL Azure DB (2019 compat level):

CREATE TABLE dbo.Properties
(
    PropertyId int, 
    PropertyName nvarchar(100),
    PropertyValue nvarchar(1000)
)

I'd like to take the data within this table and turn it into JSON using the value within the PropertyName column as the name of the JSON property, and obviously the PropertyValue value as the JSON property value.

EDIT 12/10/2021: Importantly, the values within the PropertyName column will not be predictable ahead of time.

For example, consider this data in the table (3 rows):

1, "Color", "Blue"
1, "Name", "John"
1, "Cost", 5

The above would be turned into the following JSON:

{"Color":"Blue", "Name":"John", "Cost":5}

I'm obviously able to do this with a STRING_AGG function like the following:

SELECT '{' + STRING_AGG( '"' + p.PropertyName + '": ''' + p.PropertyValue,''',')  
WITHIN GROUP (ORDER BY p.PropertyName) + '}' AS MyJson
FROM dbo.Properties p
GROUP BY p.Id

But I was hoping to use one of the build in JSON functions rather than hack together a big string.

3

1 Answer 1

3

FOR JSON AUTO works from the column names, so one method to get your desired result would be to PIVOT the property names into columns. For example:

SELECT Color, [Name], Cost 
FROM dbo.Properties
PIVOT ( MAX( PropertyValue ) For PropertyName In ( [Color], [Name], Cost ) ) pvt
FOR JSON AUTO;

My results:

results

Of course this is only convenient if your JSON attributes / column names are always known and it's a simple example. For more complex examples, you are probably looking at dynamic pivot, or dynamic SQL and your STRING_AGG example isn't so bad.

Sign up to request clarification or add additional context in comments.

4 Comments

I neglected to say in my original question that the property names aren't predictable. In other words, I won't know it's Color, Name, and Cost.
Fair enough. You’d just be looking at a dynamic pivot then.
Also, that returns an array instead of an object.
Feel free to add the WITHOUT_ARRAY_WRAPPER for your particular use case!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.