使用 T-SQL 解析 JSON

Posted

技术标签:

【中文标题】使用 T-SQL 解析 JSON【英文标题】:Parsing JSON with T-SQL 【发布时间】:2019-08-08 07:48:53 【问题描述】:

我希望只选择 JSON 字符串中的每个值名称和值,并转入 SQL 中的单独列,以便我可以轻松地将它们传递到 powershell 字符串以发送到外部 API

DECLARE @json NVARCHAR(MAX)

SET @json='  "InsertRecordData":   "data":   "AdditionalData":   "DataObjects":   "ObjData":   "Name": "coll_exclude",  "Fields":   "FieldData1":   "Name": "agreement",  "Value": "1234"  ,  "FieldData2":   "Name": "system",  "Value": "live"  ,  "FieldData3":   "Name": "date_added",  "Value": "2019-08-01"  ,  "FieldData4":   "Name": "time_added",  "Value": "11:20"                ';

SELECT *
FROM OPENJSON(@json,'$.InsertRecordData.data.AdditionalData.DataObjects.ObjData.Fields')

所以我想看看

Agreement   System    Date_added   time_added

1234           live      2019-08-01   11:20

【问题讨论】:

【参考方案1】:

使用 mssql pivot()

DECLARE @json NVARCHAR(MAX)

SET @json='  "InsertRecordData":   "data":   "AdditionalData":   "DataObjects":   "ObjData":   "Name": "coll_exclude",  "Fields":   "FieldData1":   "Name": "agreement",  "Value": "1234"  ,  "FieldData2":   "Name": "system",  "Value": "live"  ,  "FieldData3":   "Name": "date_added",  "Value": "2019-08-01"  ,  "FieldData4":   "Name": "time_added",  "Value": "11:20"                ';


select [agreement], [system], [date_added], [time_added] from
(
    SELECT json_value(js.value, '$.Name') as Titles, json_value(js.value, '$.Value') as val
    FROM OPENJSON(@json,'$.InsertRecordData.data.AdditionalData.DataObjects.ObjData.Fields') as js) as SourceTb
PIVOT
(
    max(val)
    FOR Titles in ([agreement], [system], [date_added], [time_added])
) as PivotTable

【讨论】:

太好了.. 谢谢

以上是关于使用 T-SQL 解析 JSON的主要内容,如果未能解决你的问题,请参考以下文章

T-SQL 以表格格式解析 XML 响应

30分钟全面解析-SQL事务+隔离级别+阻塞+死锁

如何解析从 T-SQL 查询返回的行

30分钟全面解析-SQL事务+隔离级别+阻塞+死锁

解析地址:模仿这 8 行 Perl 的 T-SQL 代码?

T-SQL All-At-Once 操作解析