简体   繁体   English

解析数组SQL Server中的嵌套JSON对象

[英]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. 我正在尝试解析数组中的嵌套JSON对象,但无法获得所需的结果。

This is a sample of the JSON I have and how I am parsing it: 这是我拥有的JSON的示例以及如何对其进行解析:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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