0

Let's say we have these data

CREATE TABLE [dbo].[tValues]
(
    [cValue] [VARCHAR](50) NULL
) ON [PRIMARY]

INSERT INTO [dbo].[tValues] ([cValue]) 
VALUES ('red'), ('green'), ('blue'), ('brown')

From this query:

SELECT 
    (JSON_QUERY((SELECT 
                     'Ball' AS title, 
                     '20cm' AS size,
                     (SELECT cValue FROM tValues FOR JSON PATH) AS [colors]
                 FOR JSON PATH))) AS product
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

I got this JSON result:

{
    "product": [
                 { "title":"Ball", 
                   "size":"20cm", 
                   "colors": [
                                { "cValue": "red" },
                                { "cValue": "green" },
                                { "cValue": "blue" },
                                { "cValue": "brown" }
                             ]
                 }
               ]
}

But I need without column names and curly brackets in colors tag like this:

{
    "product": [
                  {
                      "title": "Ball",
                      "size": "20cm",
                      "colors": [ "red", "green", "blue", "brown" ]
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  }
               ]
}

How can I do that?

1
  • 2
    Starting with SQL-Server 2017 there is STRING_AGG(), but really, this should've been included into the FOR JSON syntax... Commented Nov 4, 2019 at 8:50

2 Answers 2

3

One possible solution is to use for xml path with stuff to build your array:

SELECT 
    (JSON_QUERY((SELECT 
                     'Ball' AS title, 
                     '20cm' AS size,
                      JSON_QUERY(
                    '[' + STUFF(( SELECT ',' + '"' + cValue + '"' 
                    FROM tValues 
                    FOR XML PATH('')),1,1,'') + ']' ) AS [colors]
                 FOR JSON PATH)

                 )) AS product
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

Result:

{
   "product":[
      {
         "title":"Ball",
         "size":"20cm",
         "colors":[
            "red",
            "green",
            "blue",
            "brown"
         ]
      }
   ]
}
Sign up to request clarification or add additional context in comments.

Comments

2

My solution is in a working application for SQL Server 2016

JSON_QUERY('[' + STRING_AGG(tValues.color), ',') + ']') 'colors'

And will JSON_ARRAY in SQL Server 2022

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.