简体   繁体   中英

Parsing nested JSON objects in an array SQL Server

I am trying to parse nested JSON objects within an array, but I am having trouble getting to the results I need.

This is a sample of the JSON I have and how I am parsing it:

declare @json varchar(max) =
'{
  "requests": [
    {
      "ownertype": "admin",
      "ownerid": "111",
      "custom_fields": [
        {
          "orderid": "1"
        },
        {
          "requestorid": "5000"
        },
        {
          "LOE": "week"
        }
      ]
    },
    {
      "ownertype": "user",
      "ownerid": "222",
      "custom_fields": [
        {
          "orderid": "5"
        },
        {
          "requestorid": "6000"
        },
        {
          "LOE": "month"
        }
      ]
    }
  ]
}'

select requests.ownertype
      ,requests.ownerid
      ,cf.*
from OPENJSON(@json,'$.requests')
with (ownertype varchar(50)
     ,ownerid int
     ,custom_fields nvarchar(max) as json) requests
cross apply OPENJSON(custom_fields)
            with (orderid int,
                  LOE varchar(50)) as cf

This is the result I am trying to get:

ownertype   ownerid orderid LOE
admin       111     1       week
user        222     5       month

but this is the results I was able to achieve so far with the code above:

ownertype   ownerid orderid LOE
admin       111     1       NULL
admin       111     NULL    NULL
admin       111     NULL    week
user        222     5       NULL
user        222     NULL    NULL
user        222     NULL    month

I was actually able to solve this by defining the path and the order of the object in the array. Here is my solution if anyone cares about it:

declare @json varchar(max) =
'{
  "requests": [
    {
      "ownertype": "admin",
      "ownerid": "111",
      "custom_fields": [
        {
          "orderid": "1"
        },
        {
          "requestorid": "5000"
        },
        {
          "LOE": "week"
        }
      ]
    },
    {
      "ownertype": "user",
      "ownerid": "222",
      "custom_fields": [
        {
          "orderid": "5"
        },
        {
          "requestorid": "6000"
        },
        {
          "LOE": "month"
        }
      ]
    }
  ]
}'

select requests.ownertype
      ,requests.ownerid
      ,orderid.*
      ,loe.*
from OPENJSON(@json,'$.requests')
with (ownertype varchar(50)
     ,ownerid int
     ,orderid nvarchar(max) '$.custom_fields[0]' as json
     ,loe nvarchar(max) '$.custom_fields[2]' as json) requests
cross apply OPENJSON(orderid)
            with (orderid int '$.orderid') orderid
cross apply OPENJSON(loe)
            with (loe varchar(50) '$.LOE') loe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM