I’m trying to transform my table to JSON
My table:
DROP TABLE IF EXISTS #tmp
CREATE TABLE #tmp(AnalyticGoodsT CHAR(6), date SMALLDATETIME)
INSERT INTO #tmp(AnalyticGoodsT, date)
VALUES ('000001', '20230424'), ('000002', '20230424'), ('000003', '20230424'), ('000004', '20230424')
Required JSON format(i’m trying to group rows by date):
[
{
"Date": "24.04.2023",
"bk": [
"000001",
"000002",
"000003",
"000004"
]
}
]
The only way to do this that I found is this
SELECT REPLACE(REPLACE(x, '{"id":',''), '"}','"') FROM
(SELECT TOP 10
Date=CONVERT(varchar,date,104),
(SELECT DISTINCT id=AnalyticGoodsT FROM #tmp a2
WHERE a1.date=a2.date
FOR JSON path) AS bk
FROM #tmp a1
GROUP BY date
FOR JSON PATH) a(x)
But it seems to me that this method is completely wrong.
3
Answers
You can only simplify your statement. I don’t think, that you can build a dynamic JSON array of scalar values, so you need a text-based approach:
STRING_AGG()
,CONCAT()
andSTRING_ESCAPE()
(to escapes possible special characters).JSON_QUERY()
to prevent the escaping of the generated JSON array. As is explained in the documentation, … JSON_QUERY returns a valid JSON fragment. As a result, FOR JSON doesn’t escape special characters in the JSON_QUERY return value.FOR JSON AUTO
.T-SQL:
You can do it using
JSON_QUERY
andSTRING_AGG
to contruct the bk array andFOR JSON PATH
as follows :Demo here
Unfortunately, SQL Server does not have
JSON_AGG
. You need to use a combination ofSTRING_AGG
JSON_QUERY
andSTRING_ESCAPE
db<>fiddle
STRING_ESCAPE
is necessary to escape any invalid JSON characters, andJSON_QUERY
is necessary to prevent double-escaping.