How to validate JSON in SQL Server and C# before it reaches production

Comments 0

Share to social media

Valid JSON isn’t the same as valid business data, and SQL Server won’t always warn you when the difference matters. JSON_VALUE returns NULL for missing or mis-cased properties and can still return a value from malformed JSON, meaning bad payloads can slip through easily.

This guide shows how to validate JSON in SQL Server with ISJSON and CHECK constraints, and in C# with System.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).

ISJSON with a type argument and JSON_PATH_EXISTS need SQL Server 2022 or later; the json data 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:

  • Missing properties

  • NULL values where the application expects an object

  • Wrong data types, such as a number returned as a string

  • Changes in the JSON structure

  • Syntax errors when JSON is edited manually

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.

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.

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…

JSON support in SQL Server 2016 (the complete guide)

For high-volume tables, I would first check the performance impact, and then choose the validation strategy based on actual requirements.

Inserted payloadResult
{"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.

I would test performance, compatibility, storage and integration with the existing C# code before making the decision.

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 definitionRun 1 avgRun 2 avgApprox. slowdown vs no check
nvarchar(max), no check201 ms192 ms1×
+ CHECK ISJSON(payload, OBJECT) = 11,585 ms1,349 ms~7.5×
+ ISJSON and JSON_PATH_EXISTS($.customer.id)2,489 ms2,167 ms~11.8×
json data type (2025)2,456 ms1,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.

Automated and controlled preparation of test databases

Redgate Flyway Enterprise can automatically create a target test database at a known, correct schema version, load the designated test dataset, and deploy it securely to a test system.
Learn more & try for free

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.

InputValidateOrder 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.

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:

How to debug a failed JSON payload in SQL Server and C# (in summary)

  1. Capture the exact JSON payload that failed and compare it with the expected structure.

  2. Reproduce the issue with the same data.

  3. Validate the payload with the C# parser (JsonDocument.Parse) to see whether it’s malformed or just structurally wrong.

  4. If it looks SQL Server-related, check ISJSON, the JSON paths, and the JSON_VALUE and OPENJSON results.

  5. 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.

ProblemISJSON CHECKJSON_PATH_EXISTS CHECKjson type (2025)C# System.Text.Json
Trailing comma / malformed syntaxCaughtn/a (use ISJSON as well)Rejected (Msg 13609)Caught (AllowTrailingCommas = false)
Root isn’t an objectCaught (OBJECT)n/aNot caughtCaught (ValueKind check)
Missing or wrong-case propertyNot caughtCaughtNot caught (JSON_VALUE returns NULL)Caught
Wrong data type ("12,50" as a string)Not caughtNot caughtNot caughtCaught
Duplicate keysNot caughtNot caughtNot tested hereParser-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…

Azure SQL Native JSON Data Type: Query Techniques

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

All the latest articles, guides, podcasts, and more – delivered straight to your inbox.
Subscribe now

This document contains proprietary information and is protected by copyright law.

Copyright © 2026 Red Gate Software Limited. All rights reserved

Article tags

About the author

Syed Salman

See Profile

Syed Salman is the founder of A2Z Tools (https://a2z.tools), a collection of free online tools for developers and everyday users, including a JSON formatter, an XML formatter and a regex tester. He builds and runs the site on ASP.NET and SQL Server.

Syed's contributions

Syed's latest contributions: