SQL to JSON - array of objects to array of values in SQL 2016
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
add a comment |
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
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
add a comment |
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
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
sql json sql-server-2016
edited Jun 8 '16 at 18:48
Martin Smith
342k58574682
342k58574682
asked Jun 8 '16 at 17:00
Meghana Raj JayanarasimhaMeghana Raj Jayanarasimha
266127
266127
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
add a comment |
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
add a comment |
5 Answers
5
active
oldest
votes
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
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
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
add a comment |
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":','' ),
'"}','"' )
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
add a comment |
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.
2
Add JSON_QUERY() around REPLACE. That will disable redundant escaping
– DiGi
May 22 '17 at 14:07
add a comment |
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
STRING_AGG isn't available in SQL 2016 ?
– TaylorN
Jan 11 '18 at 23:00
add a comment |
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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
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
add a comment |
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
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
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
add a comment |
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
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
edited Aug 12 '16 at 5:17
David Tansey
4,43832241
4,43832241
answered Jun 15 '16 at 19:25
Meghana Raj JayanarasimhaMeghana Raj Jayanarasimha
266127
266127
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
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
add a comment |
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
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
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
add a comment |
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":','' ),
'"}','"' )
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
add a comment |
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":','' ),
'"}','"' )
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
add a comment |
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":','' ),
'"}','"' )
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":','' ),
'"}','"' )
answered Oct 15 '16 at 19:29
Magne RekdalMagne Rekdal
12616
12616
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
add a comment |
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
add a comment |
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.
2
Add JSON_QUERY() around REPLACE. That will disable redundant escaping
– DiGi
May 22 '17 at 14:07
add a comment |
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.
2
Add JSON_QUERY() around REPLACE. That will disable redundant escaping
– DiGi
May 22 '17 at 14:07
add a comment |
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.
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.
answered Oct 27 '16 at 21:18
CalvinDaleCalvinDale
2,01431826
2,01431826
2
Add JSON_QUERY() around REPLACE. That will disable redundant escaping
– DiGi
May 22 '17 at 14:07
add a comment |
2
Add JSON_QUERY() around REPLACE. That will disable redundant escaping
– DiGi
May 22 '17 at 14:07
2
2
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
add a comment |
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
STRING_AGG isn't available in SQL 2016 ?
– TaylorN
Jan 11 '18 at 23:00
add a comment |
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
STRING_AGG isn't available in SQL 2016 ?
– TaylorN
Jan 11 '18 at 23:00
add a comment |
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
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
answered Nov 22 '17 at 17:15
massthermassther
604
604
STRING_AGG isn't available in SQL 2016 ?
– TaylorN
Jan 11 '18 at 23:00
add a comment |
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
STRING_AGG isn't available in SQL 2016 ?
– TaylorN
Jan 11 '18 at 23:00
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Feb 8 '17 at 19:04
EricEric
637
637
add a comment |
add a comment |
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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