Skip to content
Advertisement

How to insert nested JSON array into SQL Server table

I am trying to insert a JSON file into a table using SQL Server’s “OPENJSON WITH (…” syntax). However, this file contains nested arrays, which I do not know how to handle.

Here is my JSON file:

and here is the code I tried to use:

But after I run the code, all the attributes in the table are null.

How can I insert the values into my table?

Advertisement

Answer

The syntax might be different and depends on the expected results. Of course, the destination table structure is also important. Note, that the JSON in the question has a typing error. The correct JSON is:

The error in your OPENSON() call is the wrong path – $.Person_ID instead of $. If you want to parse each nested JSON array separately, you should use OPENJSON() with explicit schema and the correct statement is:

and the result is:

But if the JSON holds the information for different persons, you should probably use OPENJSON() with default schema and a statement like the following:

with result:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement