I have a table in SQL SERVER to keep all of the users app reviews.
When the user reviews the app with 4 or 5 stars I recieve a Json like this one
{
"Calificacion": 5,
"Cuestionario": "",
"Comentarios": "",
"Application": "APLIC004"
}
and when te user gives us a 3 stars or lower review, FrontEnd sends me a Json like this one
{
"Calificacion": 0,
"Cuestionario": [
{
"Order": 1,
"Question": "string",
"Answer": true
}
{
"Order": 2,
"Question": "string",
"Answer": true
}
{
"Order": 3,
"Question": "string",
"Answer": true
}
{
"Order": 4,
"Question": "string",
"Answer": true
}
],
"Comentarios": "string",
"Application": "string"
}
the problem is that when I try to query the most recent record from a user, I get this message when the recent record has no data for the column Cuestionario
Msg 13609, Level 16, State 2, Line 114 JSON text is not properly
formatted. Unexpected character ‘.’ is found at position 0.
The query I’m using to fetch the data is the following
select TOP 1
UserId,
Fecha,
Calificacion,
JSON_QUERY(Cuestionario) Cuestionario,
Comentarios,
[Application]
from AppScores
where UserId = '00000000-0000-0000-0000-000000000000'
order by Fecha desc
for json path, WITHOUT_ARRAY_WRAPPER
2
Answers
The error message you’re encountering occurs because SQL Server expects the value in the Cuestionario column to be a well-formatted JSON object, but you’re getting an empty string when the rating is 4 or 5 stars.
fiddle
Using
JSON_QUERY
with a single parameter basically tells the compiler "this is definitely valid JSON, do not escape it". But''
is not valid JSON, nor is'.'
. You should really useNULL
or'[]'
for empty values.You can use the
ISJSON
function in aCASE
orIIF
to verify if the value is actually valid JSON.