I query API and JSON output I want to save to a SQL Server 2016 table. Here is how I simulate transforming JSON output:
When I run this:
DECLARE @J NVARCHAR(MAX) = '{"c":[4.935,4.935,4.9374,4.935,4.94],"t":[1643998980,1643999040,1643999100,1643999160,1643999220],"v":[1979,87494,9980,4382,17713]}';
SELECT [key] as jkey, value as c
FROM OPENJSON(@j, '$.c');
I get this:
jkey,c
0,4.935
1,4.935
2,4.9374
3,4.935
4,4.94
But I expect this:
jkey,c,t,v
0,4.935,1643998980,1979
1,4.935,1643999040,87494
2,4.9374,1643999100,9980
3,4.935,1643999160,4382
4,4.94,1643999220,17713
I spent hours and I could not figure it out. Please help.
CodePudding user response:
Simply join to the keys of the other keys.
DECLARE @J NVARCHAR(MAX) = '{"c":[4.935,4.935,4.9374,4.935,4.94],"t":[1643998980,1643999040,1643999100,1643999160,1643999220],"v":[1979,87494,9980,4382,17713]}'; SELECT c.[key] as jkey, c.value as c, t.value as t, v.value as v FROM OPENJSON(@j, '$.c') c LEFT JOIN OPENJSON(@j, '$.t') t ON t.[key] = c.[key] LEFT JOIN OPENJSON(@j, '$.v') v ON v.[key] = c.[key] ORDER BY jkey;
jkey c t v 0 4.935 1643998980 1979 1 4.935 1643999040 87494 2 4.9374 1643999100 9980 3 4.935 1643999160 4382 4 4.94 1643999220 17713
db<>fiddle here