Can SQL Server 2016 extract node names from JSON?
Select [key] from default OPENJSON schema.
DECLARE @json_doc nvarchar(4000) = '{"Name1":"Value1", "Name2":"Value2"}'; SELECT [key] FROM OPENJSON(@json_doc); GO
| key | | :---- | | Name1 | | Name2 |
dbfiddle here
To add to this answer.
Get all JSON keys in a column:
SELECT Keys.[key]
FROM dbo.<table_name> t
CROSS APPLY (
SELECT [key] [key]
FROM OPENJSON((SELECT t.<column_name>))
) Keys
E.g., Table:
+------------------+
| JSONValues |
+==================+
| {"myKey":1} |
+------------------+
| {"myOtherKey":1} |
+------------------+
Query Result:
+------------+
| Result |
+============+
| myKey |
+------------+
| myOtherKey |
+------------+
Get all JSON keys where JSON is array of objects:
SELECT DISTINCT Keys.[key]
FROM dbo.<table_name, sysname, sample_table> t
CROSS APPLY (
SELECT x.[value] [value]
FROM OPENJSON((SELECT t.<json_colum_name, sysname, sample_column>)) x
) ArrayJSON
CROSS APPLY (
SELECT [key] [key]
FROM OPENJSON((SELECT ArrayJSON.[value])) x
) Keys
Table:
+----------------------------+
| JSONValues |
+============================+
| [{"myKey":1},{"myKey2":2}] |
+----------------------------+
| [{"myKey3":3}] |
+----------------------------+
Query Result:
+--------+
| Result |
+========+
| myKey |
+--------+
| myKey2 |
+--------+
| myKey3 |
+--------+