0

I have JSON like

{  
    "url": {
        "web_categories": [{ "id": 226 } , { "id": 401 }]
  },  
   "account":"Basic"  
}

I would like to output in SQL a column that contains the IDs of all web_categories a URL was matched to.

| webcat |
|--------|
| 226    |
| 401    |

Using SQL Server 2016 / Azure SQL DB's support for JSON, how would one achieve that?

Reproducible example

DECLARE @jsonInfo VARCHAR(MAX)  
SET @jsonInfo =N'{  
    "url": {
        "web_categories": [{ "id": 226 }]
  },  
   "account":"Basic"  
}'  

Previous iterations

select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories.id[0]')
select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories.id')
select * from openjson(@jsonInfo)  with (webcat varchar(12) '$.url.web_categories')
select * from openjson(@jsonInfo,'$.url.web_categories.id[0]')
select * from openjson(@jsonInfo,'$.url.web_categories.id')
select * from openjson(@jsonInfo,'$.url.web_categories')
select JSON_QUERY(@jsonInfo, '$.url.web_categories.id[0]') webcat
select JSON_QUERY(@jsonInfo, '$.url.web_categories.id')    webcat
select JSON_QUERY(@jsonInfo, '$.url.web_categories')       webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories.id[0]') webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories.id')    webcat
select JSON_VALUE(@jsonInfo, '$.url.web_categories')       webcat
2
  • Are you going to mark your answer as accepted? Commented Sep 12, 2016 at 21:21
  • Marked as accepted Commented Sep 13, 2016 at 8:01

1 Answer 1

2

Using the default schema, records are returned with a value column that contains JSON for each item in the array. This JSON then needs to be processed.

DECLARE @jsonInfo VARCHAR(MAX)  
SET @jsonInfo =N'{  
    "url": {
        "web_categories": [{ "id": 226 },{ "id": 411 }]
  },  
   "account":101  
}'  


 SELECT JSON_VALUE(value,'$.id') AS ids FROM OPENJSON(@jsoninfo,'$.url.web_categories')
Sign up to request clarification or add additional context in comments.

1 Comment

In this case, explicit schema mightt be better choice because it will directly cast ids to int: select id from openjson(@jsonInfo,'$.url.web_categories') with (id int)

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.