我正在尝试将 JSON 文件数据“WhitelistedOrigins”保存在 SQL 表中,但我不断收到 NULL 条目。 我使用相同的方法将属性导入到表中,尽管 JSON 的格式不同,但之前这已经有效了
JSON
"Client": {
"whiteListedOrigins": [
"file://",
"https://mobile.gtent.eu",
"https://mobile.assists.co.uk",
"https://valueadds3.active.eu",
"https://flash3.active.eu",
"https://valueadds3.assists.co.uk"
]
}
SQL
DECLARE @JSON VARCHAR(MAX)
SELECT @JSON = BulkColumn
FROM OPENROWSET
(BULK 'C:\config.json', SINGLE_CLOB)
AS A
UPDATE dbo.CommonBaseline
SET CommonBaseline.whiteListedOrigins= whiteListedOrigins
FROM OPENJSON (@JSON, '$.Client')
WITH (
whiteListedOrigins Varchar (MAX))
结果
最佳答案
您需要使用OPENJSON()在列定义中具有显式架构和 AS JSON
选项。
If you want to return a nested JSON fragment from a JSON property, you have to provide the AS JSON flag. Without this option, if the property can't be found, OPENJSON returns a NULL value instead of the referenced JSON object or array, or it returns a run-time error in strict mode.
声明:
DECLARE @Json nvarchar(max) = N'{
"Client": {
"whiteListedOrigins": [
"file://",
"https://mobile.gtent.eu",
"https://mobile.assists.co.uk",
"https://valueadds3.active.eu",
"https://flash3.active.eu",
"https://valueadds3.assists.co.uk"
]
}
}'
SELECT *
FROM OPENJSON (@JSON, '$.Client') WITH (
whiteListedOrigins nvarchar (MAX) AS JSON
)
输出:
--------------------
whiteListedOrigins
--------------------
[
"file://",
"https://mobile.gtent.eu",
"https://mobile.assists.co.uk",
"https://valueadds3.active.eu",
"https://flash3.active.eu",
"https://valueadds3.assists.co.uk"
]
注释:
您的 JSON(不含 {
和 }
)无效。
关于json - SQL Server OPENROWSET 不提取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57307578/