0

I have this data in a table:

{ "keys": [ "00170000007u8uJ" ] }

I need to extract only the value 00170000007u8uJ in a SQL Server 2016 select query.

3
  • So how to get that value? The particular column has combination of string, xml..etc so I thought it is xml. The datatype used for that column is ntext
    – Vinay
    Commented Aug 14, 2020 at 13:00
  • Add the SQL Server version to your question.
    – Dan Guzman
    Commented Aug 14, 2020 at 13:09
  • SQL Server 2016
    – Vinay
    Commented Aug 14, 2020 at 13:18

1 Answer 1

1

This should do it

declare @json           nvarchar(max)=N'{ "keys": [ "00170000007u8uJ" ] }';

select [value] from openjson(json_query(@json, N'$.keys'));

If the JSON is in a table then like this

create table #temp_json(json_col        nvarchar(max));
insert #temp_json(json_col) values (N'{ "keys": [ "00170000007u8uJ" ] }');

select [value] 
from
  #temp_json tj
 cross apply
  openjson(json_query(tj.json_col, N'$.keys'));
2
  • Where can I add the table in your query?
    – Vinay
    Commented Aug 14, 2020 at 13:26
  • @Vinay, and of course, specify your table name instead of #temp in the FROM clause. Note that the query will return multiple rows when the array has multiple keys. Also, the query will fail if you pass invalid JSON (e.g. an XML value).
    – Dan Guzman
    Commented Aug 14, 2020 at 14:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.