1

Is it possible to use for json path to format rows in a JSON array format?

I have a column like this

Col1
====
abc
def
ghi
jkl

and I want to format it like this

{"Col1":["abc","def","ghi","jkl"]}

I have so far gotten it to look like this

{["Col1":"abc","Col1":"def","Col1":"ghi","Col1":"jkl"]}

using this code

select col1 from table for json path 
1
  • While asking a question, you need to provide a minimal reproducible example: (1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements. (2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL. (3) Desired output, based on the sample data in the #1 above. (4) Your SQL Server version (SELECT @@version;). Commented Dec 28, 2021 at 18:44

1 Answer 1

4

With a bit of string manipulation.

Creating a simple array seems like a missed opportunity.

Select Col1 = json_query('["'+string_agg(string_escape(Col1,'json'), '","') +'"]')
 From  YourTable
  For  json path, Without_Array_Wrapper

Results

{"Col1":["abc","def","ghi","jkl"]}

If your version is <2017, string_agg() would not be available. However, you can use the stuff()/xml approach

Select Col1 = json_query('["'+stuff((Select concat('","',string_escape(Col1,'json'))  
                                      From  YourTable 
                                      For XML Path ('')),1,3,'')+'"]')
   For  json path, Without_Array_Wrapper
Sign up to request clarification or add additional context in comments.

5 Comments

I won't lie, it feels like there should be a less clunky method, but I can't think of one.
SQL Server 2022 is promising to enhance JSON API functionality.
Sad Guess I just have to jank my way through it lol!
For XML Path (''), TYPE).value('text()[1]','nvarchar(max)') would be wise, to avoid XML escaping
@Larnu Two things that are really badly missing about SQL Server's JSON functionality: JSON_AGG as here, and JSON_OBJECT_AGG for property/value pairs

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.