-1

I am trying to Parse Table data into JSON and in the process want to skip the Table Column Names in the Post conversion to JSON. Below is the sample Snippet.

DECLARE @table1 TABLE (k1 nvarchar(max), v1 nvarchar(max))

-- Note k1 is unique
INSERT INTO @table1 (k1,v1) VALUES( 'Apple', 'One')
INSERT INTO @table1 (k1,v1) VALUES( 'Banana', 'Two')
INSERT INTO @table1 (k1,v1) VALUES( 'Orange', 'Three')

SELECT k1, v1 FROM @table1
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

--output: {"k1":"Apple","v1":"One"},{"k1":"Banana","v1":"Two"},{"k1":"Orange","v1":"Three"}
-- Expected: {"Apple","One"},{"Banana","Two"},{"Orange","Three"}

Appreciate direction!

1

1 Answer 1

1

--string concatenation&aggregation (string_agg() for sql2017&later or for xml path() for sql2016)

select string_agg(concat('{"', string_escape(k1, 'json'), '":"', string_escape(v1, 'json'), '"}'), ',') /*within group (order by k1)*/
from @table1
Sign up to request clarification or add additional context in comments.

Comments

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.