1

I've been working on converting some of my XML based stored procedures to JSON, but I'm running into an issue.

With OPENXML, I had access to mp:id, so when I was parsing an XML, I could access an element and its position in the XML in my query.

I'd like to do something similar with OPENJSON. Here's an example

DECLARE @JSON VARCHAR(MAX) =
'[
  {"Fruit":"Apple"},
  {"Fruit":"Banana"},
  {"Fruit":"Pineapple"}
]'

SELECT Fruit
FROM OPENJSON(@JSON,'$')
    WITH (Fruit VARCHAR(24) '$.Fruit')

For each fruit, I'd like to have its position as well (i.e., 1 for apple, 2 for banana, etc).

Does anyone know how to do this with OPENJSON?

1 Answer 1

3

Use OPENJSON without the WITH to project the position of each element. eg

DECLARE @JSON VARCHAR(MAX) =
'[
  {"Fruit":"Apple"},
  {"Fruit":"Banana"},
  {"Fruit":"Pineapple"}
]'

SELECT cast([key] as int) ix, json_value(value,'$.Fruit') Fruit
FROM OPENJSON(@JSON,'$')
    

outputs

ix          Fruit
----------- -------------
0           Apple
1           Banana
2           Pineapple
    
1
  • 2
    Frankly speaking, it is quite silly that there is no way to access [key] if an explicit schema via WITH clause is provided. mp:id works with an explicit schema, but whatever. Thank you for your help. Dec 16, 2021 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.