2

Given the following JSON stored in a nvarchar(max) column, how to generate the table shown? I can make is for if the nested object is an [], an array, but not a structure {}

DECLARE @JSON AS NVARCHAR(MAX);

SET  @JSON = N'{
    "ACCOUNT": 1
,   "USERS" : {
        "BOB" : 1
    ,   "JOHN" : 2
    ,   "RODGER" : 3
    }
}';


SELECT JSON_QUERY(@JSON,'$.USERS')


ACCOUNT   USER     USER_VALUE
================================
    1     BOB          1
    1     JOHN         2
    1     RODGER       3
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Peter
  • 95
  • 7

1 Answers1

2

You may try with the next approach using OPENJSON (with an explicit structure for ACCOUNT and USERS columns) and additional CROSS APPLY:

-- JSON
DECLARE @JSON AS NVARCHAR(MAX);
SET  @JSON = N'{
    "ACCOUNT": 1
,   "USERS" : {
        "BOB" : 1
    ,   "JOHN" : 2
    ,   "RODGER" : 3
    }
}';

-- Statement
SELECT i.ACCOUNT, v.[key] AS [USER], v.[value] AS USER_VALUE
FROM OPENJSON(@json) 
WITH (
   ACCOUNT int '$.ACCOUNT',
   USERS nvarchar(max) '$.USERS' AS JSON
) i
CROSS APPLY (
   SELECT *
   FROM OPENJSON(i.USERS)
) v

Output:

ACCOUNT USER    USER_VALUE
1       BOB     1
1       JOHN    2
1       RODGER  3
Zhorov
  • 28,486
  • 6
  • 27
  • 52