1

I want to parse the below json values.

DECLARE @json NVARCHAR(MAX)
SET @json =  
N'[{"ID":1,"Roles":[1,2]},{"ID":2"Roles":[1,2,3]},{"ID":3,"Roles":[1,2,3,4]}]' 

i want to display below output

Required Output
ID ROLES
1  1
1  2
2  1
2  2
2  3
3  1
3  2
3  3
3  4

I want query for this.

2
  • Your JSON isn't syntactically valid, and you have two entries for ID 1 -- the latter is easily fixed with a DISTINCT, but is it actually right? Commented Oct 22, 2018 at 10:53
  • sorry.ID will not be duplicate.it will be 3 for third one.i changed in the question now.Please check now. Commented Oct 22, 2018 at 10:55

2 Answers 2

1

An OPENJSON with a WITH unrolls the outer layer, then a regular one can be used to unroll the arrays. (The alias isn't strictly necessary, I just think it's clearer, and it becomes necessary if you have to peel even more layers.)

SELECT ID, R.[Value] AS [Role]
FROM OPENJSON(@json) WITH (
    ID INT, 
    [Roles] NVARCHAR(MAX) AS JSON
)
CROSS APPLY OPENJSON([Roles]) R
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

DECLARE @json NVARCHAR(MAX)
SET @json =  
N'[{"ID":1,"Roles":[1,2]},{"ID":2, "Roles":[1,2,3]},{"ID":3,"Roles":[1,2,3,4]}]'


SELECT pvt.[ID]
      ,roles.value
FROM
(
    SELECT js.[key] as [key_id]
          ,roles.[key]
          ,roles.value
    FROM OPENJSON(@json) js
    CROSS APPLY OPENJSON(js.value) roles 
) DS
PIVOT
(
    MAX([value]) FOR [key] IN ([ID], [Roles])
) PVT
CROSS APPLY OPENJSON(pvt.roles) roles 

enter image description here

or just this:

SELECT JSON_VALUE(js.value, '$.ID')
      ,ds.[value]
FROM OPENJSON(@json) js
CROSS APPLY OPENJSON(JSON_QUERY(js.value, '$.Roles')) ds;

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.