0

I want to loop through data to get taggedEntityName and taggedEntityId:

{
    "data": [
              {
                  "taggedEntityName": "Organization",
                  "taggedEntityId": [
                                      145642,
                                      145625
                   ],
                  "index": 0
             },
            {
                 "taggedEntityName": "Job",
                 "taggedEntityId": [
                                      221138
                                   ],
                 "index": 1
             }
           ]
 }
1
  • Hi, please provide some sample data and excepted result and current result. Or more explain in what your're trying to do. stackoverflow.com/questions/55476808/… Commented Apr 10, 2020 at 11:14

1 Answer 1

2

If you use SQL Server 2016+, you need to use OPENJSON() to parse the input JSON. The structure of the input JSON is always important and in this specific case you need to use OPENSJON() with explicit schema twice:

JSON:

DEClARE @json nvarchar(max) = N'{
    "data": [
              {
                  "taggedEntityName": "Organization",
                  "taggedEntityId": [
                                      145642,
                                      145625
                   ],
                  "index": 0
             },
            {
                 "taggedEntityName": "Job",
                 "taggedEntityId": [
                                      221138
                                   ],
                 "index": 1
             }
           ]
 }'

Statement:

 SELECT j1.taggedEntityName, j2.taggedEntityId
 FROM OPENJSON(@json, '$.data') WITH (
    taggedEntityName varchar(50) '$.taggedEntityName',
    taggedEntityId nvarchar(max) '$.taggedEntityId'  AS JSON
 ) j1
 CROSS APPLY OPENJSON(j1.taggedEntityId) WITH (
    taggedEntityId int '$'
 ) j2

Result:

taggedEntityName  taggedEntityId
Organization      145642
Organization      145625
Job               221138
Sign up to request clarification or add additional context in comments.

2 Comments

I think I will go through this solution.. this is what I was looking for.. :) Once again Thank you so much
@susmitarai Glad to help!

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.