Peter
Peter

Reputation: 95

How to I return multiple rows from a nested JSON object stored in a table

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

Upvotes: 2

Views: 855

Answers (1)

Zhorov
Zhorov

Reputation: 30003

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

Upvotes: 2

Related Questions