Share via

When processing JSON using SQL, is there an easy way to process a string containing multiple chunks of JSON

Greg Booth 1,536 Reputation points
2022-01-27T17:10:03.447+00:00

I am trying to process some files that contain JSON. I am importing the file contents into a table (using SSIS - import column) - one row in the table per file - so the JSON for each file is held in a column.
I was expecting that the JASON in each file was just that - some JSON - for example { "label1":"value1",..."labeln":"valuen"} etc - so that this value could be read into a variable (in T-SQL) and then the JSON processed using SELECT * FROM OpenJson(@json ) etc.
However what the file contains is
[ {first bit of json},[2nd bit of json},{ nth bit of json} ]
i.e. any number of bits of json seperated by comma, all enclosed by [ ]

I can remove the [ ] easily - and i could try splitting out the json bits using { as a string delimiter - but there is a risk that there is a { character in the actual json.

As far as i know SQL (we are using sql 2016) JSON processing wont help my parse a sting with multiple comma seperated json strings as described.

Can anyone else see a simpler way of processing strings that contain multiple bits of json ?

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


Answer accepted by question author

Viorel 127K Reputation points
2022-01-27T17:17:05.147+00:00

I think that it is a valid JSON, because '[ ]' denotes an array.

Check an example of processing arrays:

declare @json varchar(max) = '[ { "labelA1": "valueA1", "labelA2": "valueA2" }, { "labelB1": "valueB1", "labelB2": "valueB2" } ]'

select r.[key] as [label], r.[value]
from openjson(@json) a
cross apply openjson(a.value) r

/*
Result:

label     value
-------------------
labelA1    valueA1
labelA2    valueA2
labelB1    valueB1
labelB2    valueB2
*/

It depends on what result do you expect from your data.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.