1

I have below json in sql:

declare @jObject as nvarchar(max)='{
    "StudentData": [
        {
            "StudentID":5000,
            "StudentName":"xyz"

        },
        {
            "StudentID":5001,
            "StudentName":"abc"

        }
        ]

}'

I want to write select query such that :-

StudentID  StudentName
5000        xyz
5001        abc 

I tried below query :-

SELECT *  
FROM OPENJSON(@jObject) 
WITH (StudentID int '$.StudentID',StudentName varchar(50) '$.StudentName')

But this is returning me single row and null values for both columns. Please help.

Also tried below which is not working :-

EDIT 1 :-

SELECT *  
FROM OPENJSON(@jObject) 
WITH (StudentID int '$.StudentData.StudentID',StudentName varchar(50) '$.StudentData.StudentName')
2
  • You have an object with a StudentData property which contains objects with StudentID, ` StudentName` properties. Try '$.StudentData.StudentID' Commented Feb 2, 2018 at 12:54
  • @PanagiotisKanavos not working.. please see Edit1 Commented Feb 2, 2018 at 12:57

2 Answers 2

3

Your JSON string contains an object with a StudentData property which contains an array of objects with StudentID, StudentName properties. You need to query the contents of the StudentData property, not the root object.

To do that, pass the property's path to OPENSJON :

SELECT *  
FROM OPENJSON(@jObject,'$.StudentData') 
WITH (
    StudentID int '$.StudentID',
    StudentName varchar(50) '$.StudentName')

The result is :

StudentID   StudentName
5000        xyz
5001        abc
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sharing answer and your valuable time :)
0

Note :- Answer suggested by @Panagiotis Kanavos worked 100%

I tried below query by myself and it also worked :-

SELECT    StudentID ,StudentName 
FROM OPENJSON(@jObject) 
WITH (StudentData nvarchar(max) AS JSON)
CROSS APPLY 
            OPENJSON (StudentData)
            WITH ( StudentName nvarchar(max), StudentID int)

1 Comment

You are parsing the object twice in this case

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.