0

I have a CSV with some columns, one of them with JSON content. Can I query this JSON column with special handling?

An example below: ei

My goal is to run a query (openrowset documentation) and get output similar to this.

ID Name
0 Valarie Strickland
1 Mathews Harrison
2 Cecilia Giles
CHEEKATLAPRADEEP
  • 12,191
  • 1
  • 19
  • 42

1 Answers1

1

I tried to reproduce the same in my environment.

My sample data:

enter image description here

to convert the column with nested Json in the form of table. First, I created variable with nvarchar(max). set the select Querys value to it.

DECLARE @json nvarchar(max)
SET @json = (SELECT
TOP  100 *
FROM
OPENROWSET(
BULK  'https://dlsg2p.dfs.core.windows.net/fsn2p/jsoncolumn.csv',
FORMAT = 'CSV',
PARSER_VERSION = '2.0',
firstrow=3
) AS [result])

with below statement checking the value is assigned properly to variable.

select @json as JSON

Using CROSS APPLY for converting Json to table format:

SELECT b.id as ID ,b.name  as  Name
FROM
OPENJSON(@json)
WITH
(
friends NVARCHAR(MAX) AS JSON
) AS a
CROSS  APPLY
OPENJSON(a.friends)
WITH
(
id INT,
name  VARCHAR(MAX)
) AS b;

Execution:

enter image description here

Output:

enter image description here

Pratik Lad
  • 4,343
  • 2
  • 3
  • 11