3

I'm after running into some trouble parsing a set of JSON documents using SQL Server 2017.

I've encountered a nested array (sample below) within a document which uses dynamic ObjectId's i.e. 123 as the object Key as opposed to using a static key i.e. Category and then having a separate key:value to ref the ObjectId.

As a result I can't extract the items to a table using the regular CROSS APPLY OPENJSON syntax without specifying each individual Object Id (there are thousands)?

Is there a way to do this without referencing each ObjectId explicitly ideally i'd like to return all product items in a table and just have a field withe the categoryId.

 "ProductItems": {
            "123": [
              {
                "item": "13663"
              }
            ]
            "124": [
              {
                "value": "2336"
              },
              {
                "value": "3667"
              }             
            ],
            "453": [
              {
                "value": "8667"
              },
              {
                "value": "1956"
              }
            ]
          }
2
  • 1
    Shouldn't the brackets at the "ProductItems" level be square brackets since it is an array? Commented Mar 15, 2018 at 13:30
  • I double checked the source this reflects whats there .... It might have been more accurate if i stated that the ProductItems is an object that has a nested array of categories containing items Commented Mar 15, 2018 at 17:19

1 Answer 1

2

Try something like this:

DECLARE @x NVARCHAR(MAX)=
'{"ProductItems":{
"123": [
    {
    "item": "13663"
    }
],
"124": [
    {
    "value": "2336"
    },
    {
    "value": "3667"
    }             
],
"453": [
    {
    "value": "8667"
    },
    {
    "value": "1956"
    }
]
}}'

SELECT j2.*, j3.* 
FROM OPENJSON(@x) j1
CROSS APPLY OPENJSON(j1.Value) j2
CROSS APPLY OPENJSON(j2.Value) j3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.