Output ordinal position

Ryan Abbey 1,186 Reputation points
2021-11-11T22:48:00.557+00:00

Given a JSON string containing an array, is there any way to output the ordinal position of each element in the array?

"arrayelem": [{"name": "ColumnX"},
{"name": "ColG"},
{"name": "ColHIG"}]

So given above, I want to get output

Name Ordinal

ColumnX 0 (or 1... just right order important)
ColG 1
ColHIG 2

Using row_number() over (order by (select 1)) gives me the perceived correct order but how certain can we be it will always be the correct order? Is there a more definitive option?

I've added synapse as a tag as the requirement is for processing within Synapse so if there is an easy solution that can be done in Data Factory or similar (not spark due to ramp up times), I'm ears on that too

Azure Synapse Analytics
Azure Synapse Analytics
An Azure analytics service that brings together data integration, enterprise data warehousing, and big data analytics. Previously known as Azure SQL Data Warehouse.
5,378 questions
Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Guoxiong 8,206 Reputation points
    2021-11-12T00:28:26.723+00:00

    Based on the Microsoft documentation, the OPENJSON() function with the default schema returns Key/Value pair and the type of the Value. So you may use the key as the Ordinal. Here is the example:

    DECLARE @json nvarchar(max) = N'
    {
        "arrayelem": [
            {"name": "ColumnX"},
            {"name": "ColG"},
            {"name": "ColHIG"}
        ]
    }
    ';
    
    SELECT JSON_VALUE([Value], '$.name') AS [Name], [key] AS Ordinal
    FROM OPENJSON(@json, '$.arrayelem');
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

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