This question is based on information from the JSON data in SQL Server article from the online documentaion:
DECLARE @json NVARCHAR(MAX);
SET @json = N'[
{"id": 2, "info": {"name": "John", "surname": "Smith"}, "age": 25},
{"id": 5, "info": {"name": "Jane", "surname": "Smith"}, "dob": "2005-11-04T12:00:00"}
]';
SELECT *
FROM OPENJSON(@json)
WITH (
id INT 'strict $.id',
firstName NVARCHAR(50) '$.info.name',
lastName NVARCHAR(50) '$.info.surname',
age INT,
dateOfBirth DATETIME2 '$.dob'
);
Each line contained in the WITH
clause appears to be composed of:
- The Alias such as
firstName
- The DataType such as
NVARCHAR(50)
- The JSON column name such as
'$.info.name'
Is there a way to parse the JSON string into columns without having to explicitly define each column?
In other words, the JSON string contains the column names, for my purposes the Alias could have the same name as the JSON string column name.
WITH
at all then you get three columns:key
value
andtype
, each row is one property of the object (or one object in an array). This may still be useful for you in order to dynamically retrieve specific keys. If you give more detail on your use case there may be something to be done. Do you need the actual columns coming out of your function to be dynamic, or is it just that you want to get the data from the JSON dynamically?OPENJSON
will only break open one level. You can get a full graph by using a recursive CTE to recursively open each array or object, for example dbfiddle.uk/…. Is this what you wanted? It's very unclear what your actual wanted results are. Please show what you are actually trying to achieve