在SQL Server 2016中打开ndJSON格式

时间:2018-05-14 21:36:02

标签: sql json sql-server sql-server-2016 ndjson

如何在SQL Server 2016中打开ndJSON格式?我可以使用JSON格式打开,但对于如何使用ndJSON进行操作一无所知。

SQL Server中是否有特定功能可以执行此操作,还是有其他方法?

Declare @JSON varchar(max)

SELECT @JSON = BulkColumn
FROM OPENROWSET (BULK 'C:\examplepath\filename.JSON', SINGLE_CLOB) as j


Select * FROM OPENJSON(@JSON)
With (House varchar(50), 
      Car varchar(4000) '$.Attributes.Car',
      Door varchar(4000) '$.Attributes.Door',
      Bathroom varchar(4000) '$.Attributes.Bathroom' ,
      Basement varchar(4000) '$.Attributes.Basement' ,
      Attic varchar(4000) '$.Attributes.Attic'
      ) as Dataset
Go

JSON格式:

[

{"House":"Blue","Attributes":{"Car":"Camry","Door":"Small","Bathroom":"Medium","Basement":"Dark","Attic":"1"}},
{"House":"Red","Attributes":{"Car":"Thunderbird","Door":"Large","Bathroom":"Small","Basement":"Light","Attic":"4"}}

]

ndJSON格式:

{"House":"Blue","Attributes":{"Car":"Camry","Door":"Small","Bathroom":"Medium","Basement":"Dark","Attic":"1"}}
{"House":"Red","Attributes":{"Car":"Thunderbird","Door":"Large","Bathroom":"Small","Basement":"Light","Attic":"4"}}

1 个答案:

答案 0 :(得分:3)

您可以使用FORMATFILE子句:

SELECT  House, Car, Door, Bathroom, Basement, Attic   
FROM OPENROWSET (BULK 'D:\ndjson\ndjson.json', FORMATFILE= 'D:\ndjson\csv.fmt' ) as j
  CROSS APPLY OPENJSON(json) With 
  (   House    varchar(50), 
      Car      varchar(4000) '$.Attributes.Car',
      Door     varchar(4000) '$.Attributes.Door',
      Bathroom varchar(4000) '$.Attributes.Bathroom' ,
      Basement varchar(4000) '$.Attributes.Basement' ,
      Attic    varchar(4000) '$.Attributes.Attic'
  ) as Dataset

文件 csv.fmt 包含:

13.0
1
1 SQLCHAR 0 0 "\r\n" 1 json ""

结果:

enter image description here

有关this MSDN博客的更多信息