Valid JSON isn’t the same as valid business data, and SQL Server won’t always warn you when the difference matters.
JSON_VALUEreturnsNULLfor missing or mis-cased properties and can still return a value from malformedJSON, meaning bad payloads can slip through easily.This guide shows how to validate JSON in SQL Server with
ISJSONandCHECKconstraints, and in C# withSystem.Text.Json. Includes real tested examples, insert benchmarks and a rule for duplicate keys.Tested on SQL Server 2025 Express (17.0.1145.4, compatibility level 170) and .NET 8 (
System.Text.Json).
ISJSONwith a type argument andJSON_PATH_EXISTSneed SQL Server 2022 or later; thejsondata type needs SQL Server 2025.
Why skipping JSON validation causes production bugs
Over time, I’ve encountered various issues with JSON during API (application programming interface) integration and data processing. Sometimes, a third-party API returns a different format. Other times, some fields are missing.
These problems are usually identified from API errors, incorrect data in the database, or issues reported by users.
Most developers assume the JSON coming from their own application or from a third-party API will always be correct, so sometimes skip validation to save time.
The result? Potential issues later on: runtime errors, incorrect data, or production issues that are difficult to debug.
Common causes of bad JSON: API changes, old code, manual edits
Third-party API changes, old code, and manual database updates are the most common causes of bad JSON in my experience.
When multiple systems are integrated, each system may follow a different data structure, so we shouldn’t blindly trust the incoming data.
The problems I see most often are:
Why JSON_VALUE returns NULL instead of an error in SQL Server
One thing to be careful about is JSON_VALUE returning NULL when a property is missing or its value cannot be extracted in the expected way.
Developers sometimes assume that if the query executes successfully, the JSON is valid. We need to check JSON validity and the expected structure separately.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
DECLARE @j nvarchar(max) = N'{"Price":12.5,"tags":["a","b"],"customer":{"id":7}}'; SELECT JSON_VALUE(@j,'$.Price') AS exact, -- 12.5 JSON_VALUE(@j,'$.price') AS wrong_case, -- NULL (paths are case-sensitive) JSON_VALUE(@j,'$.missing') AS missing, -- NULL JSON_VALUE(@j,'$.tags') AS array_target, -- NULL (not a scalar) JSON_VALUE(@j,'$.customer') AS object_target; -- NULL (not a scalar) SELECT JSON_VALUE(@j,'strict $.price'); -- Msg 13608: Property cannot be found on the specified JSON path. DECLARE @bad1 nvarchar(max) = N'{"price":12.5,}'; -- ISJSON = 0 SELECT JSON_VALUE(@bad1,'$.price'); -- 12.5, no error DECLARE @bad3 nvarchar(max) = N'{"a":1,,"price":5}'; SELECT JSON_VALUE(@bad3,'$.price'); -- Msg 13609: JSON text is not properly formatted. Unexpected character '"' is found at position 8. |
I think this is risky, because getting the expected value does not mean the complete JSON document is valid.
Different parsers may handle the same invalid JSON differently, which can cause inconsistent results between the application and the database. I would validate the complete document before processing it.
|
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE #o (id int, payload nvarchar(max)); INSERT #o VALUES (1, N'{"price":10}'), -- valid (2, N'{"price":20,}'), -- trailing comma (3, N'{"Price":30}'); -- wrong case SELECT id, JSON_VALUE(payload,'$.price') AS p FROM #o; -- 1 = 10, 2 = 20, 3 = NULL (no error) SELECT SUM(CAST(JSON_VALUE(payload,'$.price') AS int)) AS total FROM #o WHERE ISJSON(payload) = 1; -- 10 |
How to validate JSON in SQL Server with ISJSON and CHECK constraints
TL;DR: To validate JSON in SQL Server, add a CHECK constraint that tests ISJSON(payload, OBJECT) = 1 for syntax and root type, and JSON_PATH_EXISTS for required properties.
I would use a CHECK constraint with ISJSON for tables where JSON data integrity is important, since it provides an additional layer of protection even if data comes from another application or from direct database queries.
You may also be interested in…
For high-volume tables, I would first check the performance impact, and then choose the validation strategy based on actual requirements.
|
1 2 3 4 5 6 7 |
CREATE TABLE dbo.Orders ( id int IDENTITY PRIMARY KEY, payload nvarchar(max) NOT NULL CONSTRAINT ck_payload_json CHECK (ISJSON(payload, OBJECT) = 1), CONSTRAINT ck_payload_price CHECK (JSON_PATH_EXISTS(payload, '$.price') = 1) ); |
| Inserted payload | Result |
|---|---|
{"price":20,} | Msg 547, ck_payload_json |
{"Price":30} | Msg 547, ck_payload_price |
[{"price":30}] | Msg 547, ck_payload_json |
{"price":30} | Inserted |
Should you use the SQL Server 2025 JSON data type?
I would consider the new JSON data type in SQL Server 2025 for new projects where compatibility isn’t an issue, but I wouldn’t migrate an existing application just because the new type is available.
You may also be interested in…
JSON indexing in SQL Server 2025: how it works and current limitations
I would test performance, compatibility, storage and integration with the existing C# code before making the decision.
|
1 2 3 4 5 6 |
CREATE TABLE dbo.Orders2 (id int IDENTITY PRIMARY KEY, payload json NOT NULL); INSERT dbo.Orders2(payload) VALUES (N'{"price":20,}'); -- Msg 13609: JSON text is not properly formatted. Unexpected character '}' is found at position 12. INSERT dbo.Orders2(payload) VALUES (N'{"price":20, "b": [1,2]}'); SELECT CAST(payload AS nvarchar(max)), JSON_VALUE(payload,'$.Price') FROM dbo.Orders2; -- {"price":20,"b":[1,2]} | NULL |
How much do ISJSON and CHECK constraints slow down inserts?
In this test, adding an ISJSON CHECK constraint made 100,000-row inserts roughly 7–8 times slower (about 1.3–1.6 seconds versus about 0.2 seconds). Adding JSON_PATH_EXISTS pushed that to roughly 11–12 times.
Meanwhile, the json data type was about 11 times slower than an unchecked column – but used 31% less storage.
The test
100,000 rows of about 350 characters each, inserted into temp tables on SQL Server 2025 Express on a desktop machine. Each result is the average of 5 runs, and the whole test was run twice.
| Table definition | Run 1 avg | Run 2 avg | Approx. slowdown vs no check |
|---|---|---|---|
nvarchar(max), no check | 201 ms | 192 ms | 1× |
+ CHECK ISJSON(payload, OBJECT) = 1 | 1,585 ms | 1,349 ms | ~7.5× |
+ ISJSON and JSON_PATH_EXISTS($.customer.id) | 2,489 ms | 2,167 ms | ~11.8× |
json data type (2025) | 2,456 ms | 1,995 ms | ~11.3× |
Storage for the same 100,000 documents: 68,706 KB as nvarchar(max), 47,558 KB as json.
What does the test show?
The test shows that how much ISJSON and CHECK constraints slow down inserts really depends on the application and the workload.
For critical business data and integration payloads, I think data integrity is more important than saving a few milliseconds.
For high-volume logging or temporary data, however, I’d benchmark the actual workload and choose the right approach that way.
It’s also recommended to avoid unnecessary repeated validation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
SELECT TOP (100000) CONCAT(N'{"id":', ROW_NUMBER() OVER (ORDER BY (SELECT 1)), N',"customer":{"id":', ABS(CHECKSUM(NEWID())) % 1000, N'},"items":[{"sku":"A-1","qty":2,"price":9.99}],"note":"', REPLICATE(N'x',200), N'"}') AS p INTO #src FROM sys.all_objects a CROSS JOIN sys.all_objects b; CREATE TABLE #n (payload nvarchar(max) NOT NULL); CREATE TABLE #c (payload nvarchar(max) NOT NULL CHECK (ISJSON(payload, OBJECT) = 1)); CREATE TABLE #c2 (payload nvarchar(max) NOT NULL CHECK (ISJSON(payload, OBJECT) = 1 AND JSON_PATH_EXISTS(payload,'$.customer.id') = 1)); CREATE TABLE #t (payload json NOT NULL); -- SQL Server 2025 only DECLARE @t0 datetime2 = SYSDATETIME(); INSERT #n SELECT p FROM #src; PRINT CONCAT('no check: ', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms'); SET @t0 = SYSDATETIME(); INSERT #c SELECT p FROM #src; PRINT CONCAT('ISJSON: ', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms'); SET @t0 = SYSDATETIME(); INSERT #c2 SELECT p FROM #src; PRINT CONCAT('+ path: ', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms'); SET @t0 = SYSDATETIME(); INSERT #t SELECT p FROM #src; PRINT CONCAT('json type:', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms'); |
Automated and controlled preparation of test databases
How to validate JSON in C# with System.Text.Json before inserting
TL;DR: To validate JSON in C#, parse it with JsonDocument.Parse (with trailing commas and comments disallowed), then check the root type, required properties and value types before sending it to SQL Server.
I prefer validating JSON in C# before sending it to the database. I usually use System.Text.Json to parse the payload and validate the expected structure and data types.
For strongly typed APIs, I prefer DTOs with proper validation. Database validation is still important as an additional layer of protection.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System.Text.Json; static string? ValidateOrder(string json) { try { using var doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = false, CommentHandling = JsonCommentHandling.Disallow, MaxDepth = 32 }); var root = doc.RootElement; if (root.ValueKind != JsonValueKind.Object) return "Root must be a JSON object."; if (!root.TryGetProperty("price", out var price)) return "Missing required property 'price'."; if (price.ValueKind != JsonValueKind.Number) return $"'price' must be a number, got {price.ValueKind}."; if (!price.TryGetDecimal(out var p) || p < 0) return "'price' must be a non-negative decimal."; return null; // valid } catch (JsonException ex) { return $"Malformed JSON at line {ex.LineNumber}, byte {ex.BytePositionInLine}: {ex.Message}"; } } |
| Input | ValidateOrder result |
|---|---|
{"price":12.5} | null (valid) |
{"price":20,} | Malformed JSON at line 0, byte 12: … |
{"Price":30} | Missing required property ‘price’. |
{"price":"12,50"} | ‘price’ must be a number, got String. |
[{"price":1}] | Root must be a JSON object. |
{"price":-3} | ‘price’ must be a non-negative decimal. |
How SQL Server and .NET handle duplicate JSON keys
Duplicate keys are valid as far as ISJSON is concerned, but parsers disagree on which value wins. The examples below show SQL Server and .NET 8 giving different answers.
For example, one system may read the first amount value while another reads the last one. This can lead to incorrect business decisions and even security issues.
I would reject duplicate keys in important payloads instead of depending on parser behavior.
|
1 2 3 4 5 6 7 8 9 10 |
-- SQL Server SELECT ISJSON(N'{"a":1,"a":2}'); -- 1 (valid) SELECT JSON_VALUE(N'{"a":1,"a":2}','$.a'); -- 1 // .NET 8 using var d = JsonDocument.Parse("{\"a\":1,\"a\":2}"); d.RootElement.GetProperty("a"); // 2 JsonNode.Parse("{\"a\":1,\"a\":2}")!.AsObject(); // ArgumentException: An item with the same key has already been added. Key: a |
How to debug a failed JSON payload in SQL Server and C#
To debug a failed payload, I first check the actual JSON payload and compare it with the expected structure. I then reproduce the issue with the same data and validate it using the C# parser.
If it’s related to SQL Server, I check ISJSON, the JSON paths, and the JSON_VALUE and OPENJSON results.
I also check the application logs and the actual data types to identify the root cause. To find invalid rows already stored in a table, run:
|
1 |
SELECT id FROM dbo.Orders WHERE ISJSON(payload) = 0 OR payload IS NULL; -- ISJSON(NULL) is NULL, not 0 |
How to debug a failed JSON payload in SQL Server and C# (in summary)
- Capture the exact JSON payload that failed and compare it with the expected structure.
- Reproduce the issue with the same data.
- Validate the payload with the C# parser (
JsonDocument.Parse) to see whether it’s malformed or just structurally wrong. - If it looks SQL Server-related, check
ISJSON, the JSON paths, and theJSON_VALUEandOPENJSONresults. - Check the application logs and the actual data types to identify the root cause.
Should you validate JSON in the app, the database, or both?
I would recommend validating at both levels. The application should validate the structure, required fields, data types and business rules before processing the payload – and the database should enforce important data integrity rules wherever possible.
We should not depend only on application-level validation, because data can enter the database through other applications or scripts.
| Problem | ISJSON CHECK | JSON_PATH_EXISTS CHECK | json type (2025) | C# System.Text.Json |
|---|---|---|---|---|
| Trailing comma / malformed syntax | Caught | n/a (use ISJSON as well) | Rejected (Msg 13609) | Caught (AllowTrailingCommas = false) |
| Root isn’t an object | Caught (OBJECT) | n/a | Not caught | Caught (ValueKind check) |
| Missing or wrong-case property | Not caught | Caught | Not caught (JSON_VALUE returns NULL) | Caught |
Wrong data type ("12,50" as a string) | Not caught | Not caught | Not caught | Caught |
| Duplicate keys | Not caught | Not caught | Not tested here | Parser-dependent (JsonDocument accepts, JsonNode throws) |
My three rules would be:
- Never blindly trust JSON, even if it comes from your own application or a trusted API.
- Validate the structure, data types, required fields and duplicate keys where they matter.
- Test performance and edge cases with real payloads before making changes in production.
You may also be interested in…
Conclusion: valid JSON isn’t the same as valid business data
The main thing I want readers to remember is that valid JSON does not always mean valid business data.
As a software architect, I prefer validating data consistently across the application and database layers. Preventing bad data at the entry point is always better than fixing the impact later in production.
FAQs: JSON validation in SQL Server
1. Does ISJSON catch every JSON problem in SQL Server?
No. ISJSON only checks that the text is syntactically valid JSON. It does not check that required properties exist, that values have the right data types, or that keys are unique: ISJSON returns 1 for {"a":1,"a":2}. Combine it with JSON_PATH_EXISTS in a CHECK constraint, or validate structure in application code, for fuller coverage.
2. Why does JSON_VALUE return NULL instead of an error?
In the default lax mode, JSON_VALUE returns NULL when a property is missing, the key’s case doesn’t match, or the target is an array or object rather than a scalar. Add the strict keyword to the path, for example 'strict $.price', and SQL Server raises error 13608 for a missing property instead of returning NULL.
3. Should I use a CHECK constraint or the json data type to validate JSON?
On versions before SQL Server 2025, use a CHECK constraint with ISJSON on an nvarchar(max) column. SQL Server 2025’s json data type rejects malformed JSON automatically and used about 31% less storage in the test above (47,558 KB versus 68,706 KB), but inserts were slower than an unchecked column. Benchmark your own workload before migrating an existing table.
4. How do I find invalid JSON already stored in a SQL Server table?
Query for rows where ISJSON(payload) = 0 OR payload IS NULL. The NULL check matters because ISJSON(NULL) returns NULL rather than 0, so a plain ISJSON(payload) = 0 filter misses NULL values. Run it before adding a CHECK constraint to an existing table, because existing invalid rows will make the constraint fail.
5. Why do duplicate keys in JSON cause problems?
Parsers disagree on duplicate keys. In the tests above, SQL Server treated {"a":1,"a":2} as valid and JSON_VALUE returned the first value (1), while .NET 8’s JsonDocument returned the last (2) and JsonNode.Parse threw an exception. Two systems can therefore read different values from the same payload, so reject duplicate keys in important payloads.
Subscribe to the Simple Talk newsletter
This document contains proprietary information and is protected by copyright law.
Copyright © 2026 Red Gate Software Limited. All rights reserved
Load comments