![](/img/trans.png)
[英]How to fix 'JSON text is not properly formatted. Unexpected character '\' is found at position 1.' error in SQL Server
[英]SQL SERVER JSON text is not properly formatted. Unexpected character found at position 0
許多人都有這個問題,但這通常是因為 JSON 不正確。 誰能告訴我為什么這不起作用。 我希望得到一個結果集:
ONE FirstName LastName
1 John Smith
Instead, I get an empty result set and the following error message in SSMS:
Msg 13609, Level 16, State 2, Line 20
JSON text is not properly formatted. Unexpected character 'J' is found at position 0.
DECLARE @IN_JSON NVARCHAR(MAX) =
N'{
"resume": {
"mailAddress": {
"sectionOrder": 10,
"section": {
"firstName": "John",
"lastName": "Smith"
}
}
}
}'
SELECT '1' AS [One],
JSON_VALUE(a.value, '$.firstName') AS [FirstName],
JSON_VALUE(a.value, '$.lastName') AS [LastName]
FROM OPENJSON (@IN_JSON, '$.resume.mailAddress.section') AS a
由於您嘗試將JSON_VALUE()
function 應用於非 JSON 值,因此這是錯誤的。 實際上,您已經可以使用OPENJSON()
提取所需的列值,只需針對這種情況應用條件聚合,例如
SELECT '1' AS [One],
MAX(CASE WHEN [key] = 'firstName' THEN value END) AS [FirstName],
MAX(CASE WHEN [key] = 'lastName' THEN value END) AS [LastName]
FROM OPENJSON (@IN_JSON, '$.resume.mailAddress.section') AS a
-- A colleague showed me the following which works as well. And thank you again Barbaros for the very fast response.
DECLARE @IN_JSON NVARCHAR(MAX) =
N'{
"resume": {
"mailAddress": {
"sectionOrder": 10,
"section": {
"firstName": "John",
"lastName": "Smith"
}
}
}
}'
SELECT '1' AS [One]
, JSON_VALUE(@IN_JSON, '$.resume.mailAddress.section.firstName') AS [FirstName]
, JSON_VALUE(@IN_JSON, '$.resume.mailAddress.section.lastName') AS [LastName]
-- Output result set:
-- One FirstName LastName
-- 1 John Smith
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.