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

时间:2018-04-29 20:56:44

标签: json sql-server

我正在尝试解析数组中的嵌套JSON对象,但是我无法获得所需的结果。

这是我拥有的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

这是我想要的结果:

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

但这是我到目前为止用以上代码实现的结果:

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

1 个答案:

答案 0 :(得分:0)

我实际上能够通过定义数组中对象的路径和顺序来解决这个问题。如果有人关心它,这是我的解决方案:

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