SQL to JSON - array of objects to array of values in SQL 2016





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







25















SQL 2016 has a new feature which converts data on SQL server to JSON. I am having difficulty in combining array of objects into array of values i.e.,



EXAMPLE -



CREATE TABLE #temp (item_id VARCHAR(256))

INSERT INTO #temp VALUES ('1234'),('5678'),('7890')

SELECT * FROM #temp

--convert to JSON

SELECT (SELECT item_id
FROM #temp
FOR JSON PATH,root('ids'))


RESULT -



{
"ids": [{
"item_id": "1234"
},
{
"item_id": "5678"
},
{
"item_id": "7890"
}]
}


But I want the result as -



"ids": [
"1234",
"5678",
"7890"
]


Can somebody please help me out?










share|improve this question

























  • I think that might just be the way it works. You might notice that FOR JSON returns an array of key:value pairs even if we might like to have something simpler e.g. plain array of values instead of array of objects. In this case we can write simple T-SQL user defined function that removes keys from the array and return plain array:

    – Martin Smith
    Jun 8 '16 at 18:48


















25















SQL 2016 has a new feature which converts data on SQL server to JSON. I am having difficulty in combining array of objects into array of values i.e.,



EXAMPLE -



CREATE TABLE #temp (item_id VARCHAR(256))

INSERT INTO #temp VALUES ('1234'),('5678'),('7890')

SELECT * FROM #temp

--convert to JSON

SELECT (SELECT item_id
FROM #temp
FOR JSON PATH,root('ids'))


RESULT -



{
"ids": [{
"item_id": "1234"
},
{
"item_id": "5678"
},
{
"item_id": "7890"
}]
}


But I want the result as -



"ids": [
"1234",
"5678",
"7890"
]


Can somebody please help me out?










share|improve this question

























  • I think that might just be the way it works. You might notice that FOR JSON returns an array of key:value pairs even if we might like to have something simpler e.g. plain array of values instead of array of objects. In this case we can write simple T-SQL user defined function that removes keys from the array and return plain array:

    – Martin Smith
    Jun 8 '16 at 18:48














25












25








25


8






SQL 2016 has a new feature which converts data on SQL server to JSON. I am having difficulty in combining array of objects into array of values i.e.,



EXAMPLE -



CREATE TABLE #temp (item_id VARCHAR(256))

INSERT INTO #temp VALUES ('1234'),('5678'),('7890')

SELECT * FROM #temp

--convert to JSON

SELECT (SELECT item_id
FROM #temp
FOR JSON PATH,root('ids'))


RESULT -



{
"ids": [{
"item_id": "1234"
},
{
"item_id": "5678"
},
{
"item_id": "7890"
}]
}


But I want the result as -



"ids": [
"1234",
"5678",
"7890"
]


Can somebody please help me out?










share|improve this question
















SQL 2016 has a new feature which converts data on SQL server to JSON. I am having difficulty in combining array of objects into array of values i.e.,



EXAMPLE -



CREATE TABLE #temp (item_id VARCHAR(256))

INSERT INTO #temp VALUES ('1234'),('5678'),('7890')

SELECT * FROM #temp

--convert to JSON

SELECT (SELECT item_id
FROM #temp
FOR JSON PATH,root('ids'))


RESULT -



{
"ids": [{
"item_id": "1234"
},
{
"item_id": "5678"
},
{
"item_id": "7890"
}]
}


But I want the result as -



"ids": [
"1234",
"5678",
"7890"
]


Can somebody please help me out?







sql json sql-server-2016






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 8 '16 at 18:48









Martin Smith

352k60591700




352k60591700










asked Jun 8 '16 at 17:00









Meghana Raj JayanarasimhaMeghana Raj Jayanarasimha

276137




276137













  • I think that might just be the way it works. You might notice that FOR JSON returns an array of key:value pairs even if we might like to have something simpler e.g. plain array of values instead of array of objects. In this case we can write simple T-SQL user defined function that removes keys from the array and return plain array:

    – Martin Smith
    Jun 8 '16 at 18:48



















  • I think that might just be the way it works. You might notice that FOR JSON returns an array of key:value pairs even if we might like to have something simpler e.g. plain array of values instead of array of objects. In this case we can write simple T-SQL user defined function that removes keys from the array and return plain array:

    – Martin Smith
    Jun 8 '16 at 18:48

















I think that might just be the way it works. You might notice that FOR JSON returns an array of key:value pairs even if we might like to have something simpler e.g. plain array of values instead of array of objects. In this case we can write simple T-SQL user defined function that removes keys from the array and return plain array:

– Martin Smith
Jun 8 '16 at 18:48





I think that might just be the way it works. You might notice that FOR JSON returns an array of key:value pairs even if we might like to have something simpler e.g. plain array of values instead of array of objects. In this case we can write simple T-SQL user defined function that removes keys from the array and return plain array:

– Martin Smith
Jun 8 '16 at 18:48












5 Answers
5






active

oldest

votes


















15














Thanks! The soultion we found is converting into XML first -



SELECT  
JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"'
FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER





share|improve this answer


























  • I think due to the performance issue of FOR XML query it's not a good practice

    – Saman Gholami
    Jan 15 '17 at 11:03






  • 1





    we can use string_escape(item_id, N'json') to avoid producing invalid json format.

    – Zheng Xing
    Apr 3 '18 at 17:41











  • I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

    – FisNaN
    May 29 '18 at 22:37



















12














Martin!



I believe this is an even simpler way of doing it:



    SELECT '"ids": ' + 
REPLACE(
REPLACE( (SELECT item_id FROM #temp FOR JSON AUTO),'{"item_id":','' ),
'"}','"' )





share|improve this answer



















  • 1





    This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

    – harpo
    Feb 21 '17 at 6:43











  • Well, I voted it up by one :-)

    – Magne Rekdal
    Feb 22 '17 at 15:40



















5














declare @temp table (item_id VARCHAR(256))

INSERT INTO @temp VALUES ('123"4'),('5678'),('7890')

SELECT * FROM @temp

--convert to JSON

select
json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE(item_id, 'json') + '"', char(44)))) as [json]
from @temp
for json path


When we want to concatenate strings as json array then:



1) escape string - STRING_ESCAPE



2) concatenate string with comma separator - STRING_AGG, comma ascii code is 44



3) add quotation it in brackets - QUOTENAME (without param)



4) return string (with array of elements) as json - JSON_QUERY






share|improve this answer
























  • STRING_AGG isn't available in SQL 2016 ?

    – TaylorN
    Jan 11 '18 at 23:00






  • 1





    If you are running a recent version of SQL Server, this is the cleanest solution.

    – N8allan
    Jan 21 at 23:50



















3














Since arrays of primitive values are valid JSON, it seems strange that a facility for selecting arrays of primitive values isn't built into SQL Server's JSON functionality. (If on the contrary such functionality exists, I at least haven't been able to discover it after quite a bit of searching).



The approach outlined above works as described. But when applied for a field in a larger query, the array of primitives is surrounded with quotes.



E.g., this



DECLARE @BomTable TABLE (ChildNumber dbo.udt_ConMetPartNumber);
INSERT INTO @BomTable (ChildNumber) VALUES (N'101026'), (N'101027');
SELECT N'"Children": ' + REPLACE(REPLACE((SELECT ChildNumber FROM @BomTable FOR JSON PATH), N'{"ChildNumber":', N''), '"}','');


works by producing:



"Children": ["101026,"101027]


But, following the approach above, this:



SELECT
p.PartNumber,
p.Description,
REPLACE(REPLACE((SELECT
ChildNumber
FROM
Part.BillOfMaterials
WHERE
ParentNumber = p.PartNumber
ORDER BY
ChildNumber
FOR
JSON AUTO
), N'{"ChildNumber":', N''), '"}', '"') AS [Children]
FROM
Part.Parts AS p
WHERE
p.PartNumber = N'104444'
FOR
JSON PATH


Produces:



[
{
"PartNumber": "104444",
"Description": "ASSY HUB R-SER DRIV HP10 ABS",
"Children": "["101026","101027","102291","103430","103705","104103"]"
}
]


Where the Children array is wrapped as a string.






share|improve this answer



















  • 3





    Add JSON_QUERY() around REPLACE. That will disable redundant escaping

    – DiGi
    May 22 '17 at 14:07



















1














Most of these solutions are essentially creating a CSV that represents the array contents, and then putting that CSV into the final JSON format. Here's what I use, to avoid XML:



DECLARE @tmp NVARCHAR(MAX) = ''

SELECT @tmp = @tmp + '"' + [item_id] + '",'
FROM #temp -- Defined and populated in the original question

SELECT [ids] = JSON_QUERY((
SELECT CASE
WHEN @tmp IS NULL THEN ''
ELSE '[' + SUBSTRING(@tmp, 0, LEN(@tmp)) + ']'
END
))
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37708638%2fsql-to-json-array-of-objects-to-array-of-values-in-sql-2016%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    15














    Thanks! The soultion we found is converting into XML first -



    SELECT  
    JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"'
    FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids
    FOR JSON PATH , WITHOUT_ARRAY_WRAPPER





    share|improve this answer


























    • I think due to the performance issue of FOR XML query it's not a good practice

      – Saman Gholami
      Jan 15 '17 at 11:03






    • 1





      we can use string_escape(item_id, N'json') to avoid producing invalid json format.

      – Zheng Xing
      Apr 3 '18 at 17:41











    • I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

      – FisNaN
      May 29 '18 at 22:37
















    15














    Thanks! The soultion we found is converting into XML first -



    SELECT  
    JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"'
    FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids
    FOR JSON PATH , WITHOUT_ARRAY_WRAPPER





    share|improve this answer


























    • I think due to the performance issue of FOR XML query it's not a good practice

      – Saman Gholami
      Jan 15 '17 at 11:03






    • 1





      we can use string_escape(item_id, N'json') to avoid producing invalid json format.

      – Zheng Xing
      Apr 3 '18 at 17:41











    • I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

      – FisNaN
      May 29 '18 at 22:37














    15












    15








    15







    Thanks! The soultion we found is converting into XML first -



    SELECT  
    JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"'
    FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids
    FOR JSON PATH , WITHOUT_ARRAY_WRAPPER





    share|improve this answer















    Thanks! The soultion we found is converting into XML first -



    SELECT  
    JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + item_id + '"'
    FROM #temp FOR XML PATH('')),1,1,'') + ']' ) ids
    FOR JSON PATH , WITHOUT_ARRAY_WRAPPER






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 12 '16 at 5:17









    David Tansey

    4,51832242




    4,51832242










    answered Jun 15 '16 at 19:25









    Meghana Raj JayanarasimhaMeghana Raj Jayanarasimha

    276137




    276137













    • I think due to the performance issue of FOR XML query it's not a good practice

      – Saman Gholami
      Jan 15 '17 at 11:03






    • 1





      we can use string_escape(item_id, N'json') to avoid producing invalid json format.

      – Zheng Xing
      Apr 3 '18 at 17:41











    • I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

      – FisNaN
      May 29 '18 at 22:37



















    • I think due to the performance issue of FOR XML query it's not a good practice

      – Saman Gholami
      Jan 15 '17 at 11:03






    • 1





      we can use string_escape(item_id, N'json') to avoid producing invalid json format.

      – Zheng Xing
      Apr 3 '18 at 17:41











    • I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

      – FisNaN
      May 29 '18 at 22:37

















    I think due to the performance issue of FOR XML query it's not a good practice

    – Saman Gholami
    Jan 15 '17 at 11:03





    I think due to the performance issue of FOR XML query it's not a good practice

    – Saman Gholami
    Jan 15 '17 at 11:03




    1




    1





    we can use string_escape(item_id, N'json') to avoid producing invalid json format.

    – Zheng Xing
    Apr 3 '18 at 17:41





    we can use string_escape(item_id, N'json') to avoid producing invalid json format.

    – Zheng Xing
    Apr 3 '18 at 17:41













    I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

    – FisNaN
    May 29 '18 at 22:37





    I've been using this one for quite some time. Is there a shorter version works with SQL server 2016?

    – FisNaN
    May 29 '18 at 22:37













    12














    Martin!



    I believe this is an even simpler way of doing it:



        SELECT '"ids": ' + 
    REPLACE(
    REPLACE( (SELECT item_id FROM #temp FOR JSON AUTO),'{"item_id":','' ),
    '"}','"' )





    share|improve this answer



















    • 1





      This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

      – harpo
      Feb 21 '17 at 6:43











    • Well, I voted it up by one :-)

      – Magne Rekdal
      Feb 22 '17 at 15:40
















    12














    Martin!



    I believe this is an even simpler way of doing it:



        SELECT '"ids": ' + 
    REPLACE(
    REPLACE( (SELECT item_id FROM #temp FOR JSON AUTO),'{"item_id":','' ),
    '"}','"' )





    share|improve this answer



















    • 1





      This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

      – harpo
      Feb 21 '17 at 6:43











    • Well, I voted it up by one :-)

      – Magne Rekdal
      Feb 22 '17 at 15:40














    12












    12








    12







    Martin!



    I believe this is an even simpler way of doing it:



        SELECT '"ids": ' + 
    REPLACE(
    REPLACE( (SELECT item_id FROM #temp FOR JSON AUTO),'{"item_id":','' ),
    '"}','"' )





    share|improve this answer













    Martin!



    I believe this is an even simpler way of doing it:



        SELECT '"ids": ' + 
    REPLACE(
    REPLACE( (SELECT item_id FROM #temp FOR JSON AUTO),'{"item_id":','' ),
    '"}','"' )






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Oct 15 '16 at 19:29









    Magne RekdalMagne Rekdal

    15617




    15617








    • 1





      This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

      – harpo
      Feb 21 '17 at 6:43











    • Well, I voted it up by one :-)

      – Magne Rekdal
      Feb 22 '17 at 15:40














    • 1





      This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

      – harpo
      Feb 21 '17 at 6:43











    • Well, I voted it up by one :-)

      – Magne Rekdal
      Feb 22 '17 at 15:40








    1




    1





    This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

    – harpo
    Feb 21 '17 at 6:43





    This is a much better hack than any other I've seen. And unfortunately, this has reached the graveyard of feature requests.

    – harpo
    Feb 21 '17 at 6:43













    Well, I voted it up by one :-)

    – Magne Rekdal
    Feb 22 '17 at 15:40





    Well, I voted it up by one :-)

    – Magne Rekdal
    Feb 22 '17 at 15:40











    5














    declare @temp table (item_id VARCHAR(256))

    INSERT INTO @temp VALUES ('123"4'),('5678'),('7890')

    SELECT * FROM @temp

    --convert to JSON

    select
    json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE(item_id, 'json') + '"', char(44)))) as [json]
    from @temp
    for json path


    When we want to concatenate strings as json array then:



    1) escape string - STRING_ESCAPE



    2) concatenate string with comma separator - STRING_AGG, comma ascii code is 44



    3) add quotation it in brackets - QUOTENAME (without param)



    4) return string (with array of elements) as json - JSON_QUERY






    share|improve this answer
























    • STRING_AGG isn't available in SQL 2016 ?

      – TaylorN
      Jan 11 '18 at 23:00






    • 1





      If you are running a recent version of SQL Server, this is the cleanest solution.

      – N8allan
      Jan 21 at 23:50
















    5














    declare @temp table (item_id VARCHAR(256))

    INSERT INTO @temp VALUES ('123"4'),('5678'),('7890')

    SELECT * FROM @temp

    --convert to JSON

    select
    json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE(item_id, 'json') + '"', char(44)))) as [json]
    from @temp
    for json path


    When we want to concatenate strings as json array then:



    1) escape string - STRING_ESCAPE



    2) concatenate string with comma separator - STRING_AGG, comma ascii code is 44



    3) add quotation it in brackets - QUOTENAME (without param)



    4) return string (with array of elements) as json - JSON_QUERY






    share|improve this answer
























    • STRING_AGG isn't available in SQL 2016 ?

      – TaylorN
      Jan 11 '18 at 23:00






    • 1





      If you are running a recent version of SQL Server, this is the cleanest solution.

      – N8allan
      Jan 21 at 23:50














    5












    5








    5







    declare @temp table (item_id VARCHAR(256))

    INSERT INTO @temp VALUES ('123"4'),('5678'),('7890')

    SELECT * FROM @temp

    --convert to JSON

    select
    json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE(item_id, 'json') + '"', char(44)))) as [json]
    from @temp
    for json path


    When we want to concatenate strings as json array then:



    1) escape string - STRING_ESCAPE



    2) concatenate string with comma separator - STRING_AGG, comma ascii code is 44



    3) add quotation it in brackets - QUOTENAME (without param)



    4) return string (with array of elements) as json - JSON_QUERY






    share|improve this answer













    declare @temp table (item_id VARCHAR(256))

    INSERT INTO @temp VALUES ('123"4'),('5678'),('7890')

    SELECT * FROM @temp

    --convert to JSON

    select
    json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE(item_id, 'json') + '"', char(44)))) as [json]
    from @temp
    for json path


    When we want to concatenate strings as json array then:



    1) escape string - STRING_ESCAPE



    2) concatenate string with comma separator - STRING_AGG, comma ascii code is 44



    3) add quotation it in brackets - QUOTENAME (without param)



    4) return string (with array of elements) as json - JSON_QUERY







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 22 '17 at 17:15









    massthermassther

    8014




    8014













    • STRING_AGG isn't available in SQL 2016 ?

      – TaylorN
      Jan 11 '18 at 23:00






    • 1





      If you are running a recent version of SQL Server, this is the cleanest solution.

      – N8allan
      Jan 21 at 23:50



















    • STRING_AGG isn't available in SQL 2016 ?

      – TaylorN
      Jan 11 '18 at 23:00






    • 1





      If you are running a recent version of SQL Server, this is the cleanest solution.

      – N8allan
      Jan 21 at 23:50

















    STRING_AGG isn't available in SQL 2016 ?

    – TaylorN
    Jan 11 '18 at 23:00





    STRING_AGG isn't available in SQL 2016 ?

    – TaylorN
    Jan 11 '18 at 23:00




    1




    1





    If you are running a recent version of SQL Server, this is the cleanest solution.

    – N8allan
    Jan 21 at 23:50





    If you are running a recent version of SQL Server, this is the cleanest solution.

    – N8allan
    Jan 21 at 23:50











    3














    Since arrays of primitive values are valid JSON, it seems strange that a facility for selecting arrays of primitive values isn't built into SQL Server's JSON functionality. (If on the contrary such functionality exists, I at least haven't been able to discover it after quite a bit of searching).



    The approach outlined above works as described. But when applied for a field in a larger query, the array of primitives is surrounded with quotes.



    E.g., this



    DECLARE @BomTable TABLE (ChildNumber dbo.udt_ConMetPartNumber);
    INSERT INTO @BomTable (ChildNumber) VALUES (N'101026'), (N'101027');
    SELECT N'"Children": ' + REPLACE(REPLACE((SELECT ChildNumber FROM @BomTable FOR JSON PATH), N'{"ChildNumber":', N''), '"}','');


    works by producing:



    "Children": ["101026,"101027]


    But, following the approach above, this:



    SELECT
    p.PartNumber,
    p.Description,
    REPLACE(REPLACE((SELECT
    ChildNumber
    FROM
    Part.BillOfMaterials
    WHERE
    ParentNumber = p.PartNumber
    ORDER BY
    ChildNumber
    FOR
    JSON AUTO
    ), N'{"ChildNumber":', N''), '"}', '"') AS [Children]
    FROM
    Part.Parts AS p
    WHERE
    p.PartNumber = N'104444'
    FOR
    JSON PATH


    Produces:



    [
    {
    "PartNumber": "104444",
    "Description": "ASSY HUB R-SER DRIV HP10 ABS",
    "Children": "["101026","101027","102291","103430","103705","104103"]"
    }
    ]


    Where the Children array is wrapped as a string.






    share|improve this answer



















    • 3





      Add JSON_QUERY() around REPLACE. That will disable redundant escaping

      – DiGi
      May 22 '17 at 14:07
















    3














    Since arrays of primitive values are valid JSON, it seems strange that a facility for selecting arrays of primitive values isn't built into SQL Server's JSON functionality. (If on the contrary such functionality exists, I at least haven't been able to discover it after quite a bit of searching).



    The approach outlined above works as described. But when applied for a field in a larger query, the array of primitives is surrounded with quotes.



    E.g., this



    DECLARE @BomTable TABLE (ChildNumber dbo.udt_ConMetPartNumber);
    INSERT INTO @BomTable (ChildNumber) VALUES (N'101026'), (N'101027');
    SELECT N'"Children": ' + REPLACE(REPLACE((SELECT ChildNumber FROM @BomTable FOR JSON PATH), N'{"ChildNumber":', N''), '"}','');


    works by producing:



    "Children": ["101026,"101027]


    But, following the approach above, this:



    SELECT
    p.PartNumber,
    p.Description,
    REPLACE(REPLACE((SELECT
    ChildNumber
    FROM
    Part.BillOfMaterials
    WHERE
    ParentNumber = p.PartNumber
    ORDER BY
    ChildNumber
    FOR
    JSON AUTO
    ), N'{"ChildNumber":', N''), '"}', '"') AS [Children]
    FROM
    Part.Parts AS p
    WHERE
    p.PartNumber = N'104444'
    FOR
    JSON PATH


    Produces:



    [
    {
    "PartNumber": "104444",
    "Description": "ASSY HUB R-SER DRIV HP10 ABS",
    "Children": "["101026","101027","102291","103430","103705","104103"]"
    }
    ]


    Where the Children array is wrapped as a string.






    share|improve this answer



















    • 3





      Add JSON_QUERY() around REPLACE. That will disable redundant escaping

      – DiGi
      May 22 '17 at 14:07














    3












    3








    3







    Since arrays of primitive values are valid JSON, it seems strange that a facility for selecting arrays of primitive values isn't built into SQL Server's JSON functionality. (If on the contrary such functionality exists, I at least haven't been able to discover it after quite a bit of searching).



    The approach outlined above works as described. But when applied for a field in a larger query, the array of primitives is surrounded with quotes.



    E.g., this



    DECLARE @BomTable TABLE (ChildNumber dbo.udt_ConMetPartNumber);
    INSERT INTO @BomTable (ChildNumber) VALUES (N'101026'), (N'101027');
    SELECT N'"Children": ' + REPLACE(REPLACE((SELECT ChildNumber FROM @BomTable FOR JSON PATH), N'{"ChildNumber":', N''), '"}','');


    works by producing:



    "Children": ["101026,"101027]


    But, following the approach above, this:



    SELECT
    p.PartNumber,
    p.Description,
    REPLACE(REPLACE((SELECT
    ChildNumber
    FROM
    Part.BillOfMaterials
    WHERE
    ParentNumber = p.PartNumber
    ORDER BY
    ChildNumber
    FOR
    JSON AUTO
    ), N'{"ChildNumber":', N''), '"}', '"') AS [Children]
    FROM
    Part.Parts AS p
    WHERE
    p.PartNumber = N'104444'
    FOR
    JSON PATH


    Produces:



    [
    {
    "PartNumber": "104444",
    "Description": "ASSY HUB R-SER DRIV HP10 ABS",
    "Children": "["101026","101027","102291","103430","103705","104103"]"
    }
    ]


    Where the Children array is wrapped as a string.






    share|improve this answer













    Since arrays of primitive values are valid JSON, it seems strange that a facility for selecting arrays of primitive values isn't built into SQL Server's JSON functionality. (If on the contrary such functionality exists, I at least haven't been able to discover it after quite a bit of searching).



    The approach outlined above works as described. But when applied for a field in a larger query, the array of primitives is surrounded with quotes.



    E.g., this



    DECLARE @BomTable TABLE (ChildNumber dbo.udt_ConMetPartNumber);
    INSERT INTO @BomTable (ChildNumber) VALUES (N'101026'), (N'101027');
    SELECT N'"Children": ' + REPLACE(REPLACE((SELECT ChildNumber FROM @BomTable FOR JSON PATH), N'{"ChildNumber":', N''), '"}','');


    works by producing:



    "Children": ["101026,"101027]


    But, following the approach above, this:



    SELECT
    p.PartNumber,
    p.Description,
    REPLACE(REPLACE((SELECT
    ChildNumber
    FROM
    Part.BillOfMaterials
    WHERE
    ParentNumber = p.PartNumber
    ORDER BY
    ChildNumber
    FOR
    JSON AUTO
    ), N'{"ChildNumber":', N''), '"}', '"') AS [Children]
    FROM
    Part.Parts AS p
    WHERE
    p.PartNumber = N'104444'
    FOR
    JSON PATH


    Produces:



    [
    {
    "PartNumber": "104444",
    "Description": "ASSY HUB R-SER DRIV HP10 ABS",
    "Children": "["101026","101027","102291","103430","103705","104103"]"
    }
    ]


    Where the Children array is wrapped as a string.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Oct 27 '16 at 21:18









    CalvinDaleCalvinDale

    2,24631827




    2,24631827








    • 3





      Add JSON_QUERY() around REPLACE. That will disable redundant escaping

      – DiGi
      May 22 '17 at 14:07














    • 3





      Add JSON_QUERY() around REPLACE. That will disable redundant escaping

      – DiGi
      May 22 '17 at 14:07








    3




    3





    Add JSON_QUERY() around REPLACE. That will disable redundant escaping

    – DiGi
    May 22 '17 at 14:07





    Add JSON_QUERY() around REPLACE. That will disable redundant escaping

    – DiGi
    May 22 '17 at 14:07











    1














    Most of these solutions are essentially creating a CSV that represents the array contents, and then putting that CSV into the final JSON format. Here's what I use, to avoid XML:



    DECLARE @tmp NVARCHAR(MAX) = ''

    SELECT @tmp = @tmp + '"' + [item_id] + '",'
    FROM #temp -- Defined and populated in the original question

    SELECT [ids] = JSON_QUERY((
    SELECT CASE
    WHEN @tmp IS NULL THEN ''
    ELSE '[' + SUBSTRING(@tmp, 0, LEN(@tmp)) + ']'
    END
    ))
    FOR JSON PATH, WITHOUT_ARRAY_WRAPPER





    share|improve this answer




























      1














      Most of these solutions are essentially creating a CSV that represents the array contents, and then putting that CSV into the final JSON format. Here's what I use, to avoid XML:



      DECLARE @tmp NVARCHAR(MAX) = ''

      SELECT @tmp = @tmp + '"' + [item_id] + '",'
      FROM #temp -- Defined and populated in the original question

      SELECT [ids] = JSON_QUERY((
      SELECT CASE
      WHEN @tmp IS NULL THEN ''
      ELSE '[' + SUBSTRING(@tmp, 0, LEN(@tmp)) + ']'
      END
      ))
      FOR JSON PATH, WITHOUT_ARRAY_WRAPPER





      share|improve this answer


























        1












        1








        1







        Most of these solutions are essentially creating a CSV that represents the array contents, and then putting that CSV into the final JSON format. Here's what I use, to avoid XML:



        DECLARE @tmp NVARCHAR(MAX) = ''

        SELECT @tmp = @tmp + '"' + [item_id] + '",'
        FROM #temp -- Defined and populated in the original question

        SELECT [ids] = JSON_QUERY((
        SELECT CASE
        WHEN @tmp IS NULL THEN ''
        ELSE '[' + SUBSTRING(@tmp, 0, LEN(@tmp)) + ']'
        END
        ))
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER





        share|improve this answer













        Most of these solutions are essentially creating a CSV that represents the array contents, and then putting that CSV into the final JSON format. Here's what I use, to avoid XML:



        DECLARE @tmp NVARCHAR(MAX) = ''

        SELECT @tmp = @tmp + '"' + [item_id] + '",'
        FROM #temp -- Defined and populated in the original question

        SELECT [ids] = JSON_QUERY((
        SELECT CASE
        WHEN @tmp IS NULL THEN ''
        ELSE '[' + SUBSTRING(@tmp, 0, LEN(@tmp)) + ']'
        END
        ))
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Feb 8 '17 at 19:04









        EricEric

        637




        637






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37708638%2fsql-to-json-array-of-objects-to-array-of-values-in-sql-2016%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Paul Cézanne

            UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

            Angular material date-picker (MatDatepicker) auto completes the date on focus out