Azure-Sql-Database

在 SQL Server 中解壓縮 JSON 對象的最佳方法是什麼?

  • June 28, 2019

我涉足 JSON 的第 2 部分,我想將使用者添加到多個組:將 JSON 數組插入表中。

理想情況下,JSON 應該是這樣的:

   '{
   "Email": "WMogh@starfleet.gov",
   "Prefix":null,
   "FirstName": "Worf",
   "MiddleInitial": "",
   "LastName": "Mogh",
   "Suffix": "Son Of",
   "Title" :"Commander",
   "Groups": [{"0", "1", "5"}]
   }' 

目前,我可以像這樣使用 JSON 來做到這一點:

   '{
   "Email": "WMogh@starfleet.gov",
   "Prefix":null,
   "FirstName": "Worf",
   "MiddleInitial": "",
   "LastName": "Mogh",
   "Suffix": "Son Of",
   "Title" :"Commander",
   "Groups": "1,2,3,4"
   }' 

然後用以下小曲“解壓”它:

   declare @groups varchar(1000)

   select @groups = Groups from openjson(@json)
                   WITH
           (

           Groups nvarchar(100)        '$.Groups'
           )

           print @groups

   select value from string_split(@groups, ',')

它返回一個不錯的小表,如下所示:

Value
1
2
3
4

問題這是糟糕的 JSON,Web 開發人員會取笑我。

問題如何在 SQL Server 中正確解壓縮 JSON 數組?

我認為您對數組的 JSON 定義可能有點奇怪,您應該能夠像這樣解壓縮數組:

DECLARE @json                   VARCHAR( 4000 ) =  '
   {
       "Email": "WMogh@starfleet.gov",
       "Prefix":null,
       "FirstName": "Worf",
       "MiddleInitial": "",
       "LastName": "Mogh",
       "Suffix": "Son Of",
       "Title" :"Commander",
       "Groups": ["0", "1", "5"]
   }';

SELECT  ISJSON( @json );

SELECT  j.value
FROM    OPENJSON( @json, 'strict $.Groups' ) j;

價值

0

1

5

該符號"Groups":[{"0", "1", "5"}]表示在一個對像中,有一個鍵“Groups”,它的值是一個包含單個元素的數組。該元素也是一個對象,但是 -"0", "1", "5"在 JSON 上下文中沒有意義。例如:

DECLARE @json                   VARCHAR( 4000 ) =  '
   {
       "Email": "WMogh@starfleet.gov",
       "Prefix":null,
       "FirstName": "Worf",
       "MiddleInitial": "",
       "LastName": "Mogh",
       "Suffix": "Son Of",
       "Title" :"Commander",
       "Groups": [{"A": "0", "B": "1", "C": "5"}]
   }';

SELECT  ISJSON( @json );

SELECT  A = JSON_VALUE( j.value, '$.A' ),
       B = JSON_VALUE( j.value, '$.B' ),
       C = JSON_VALUE( j.value, '$.C' )            
FROM    OPENJSON( @json, 'strict $.Groups' ) j

美國廣播公司

0 1 5

引用自:https://dba.stackexchange.com/questions/241642