{"id":113998,"date":"2026-11-30T12:00:00","date_gmt":"2026-11-30T12:00:00","guid":{"rendered":"https:\/\/www.red-gate.com\/simple-talk\/?p=113998"},"modified":"2026-11-11T13:51:24","modified_gmt":"2026-11-11T13:51:24","slug":"validate-json-sql-server-isjson-csharp","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/validate-json-sql-server-isjson-csharp\/","title":{"rendered":"How to validate JSON in SQL Server and C# before it reaches production"},"content":{"rendered":"\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Valid JSON isn\u2019t the same as valid business data, and SQL Server won\u2019t always warn you when the difference matters. <code>JSON_VALUE<\/code> returns <code>NULL<\/code> for missing or mis-cased properties and can still return a value from malformed <code>JSON<\/code>, meaning bad payloads can slip through easily.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This guide shows <strong>how to validate JSON in SQL Server<\/strong> with <code>ISJSON<\/code> and <code>CHECK<\/code> constraints, and in C# with <code>System.Text.Json<\/code>. Includes real tested examples, insert benchmarks and a rule for duplicate keys.<\/p>\n\n\n\n<div id=\"callout-block_99e65c6181f4ac93a99bd026fc17ba47\" class=\"callout alignnone\">\n    <div class=\"child-last:mb-0 child-first:mt-0 bg-gray-50 dark:bg-gray-950 p-4xl my-3xl\">\n\n<p class=\"wp-block-paragraph\"><em>Tested on SQL Server 2025 Express (17.0.1145.4, compatibility level 170) and .NET 8 (<code>System.Text.Json<\/code>). <\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em><code>ISJSON<\/code> with a type argument and <code>JSON_PATH_EXISTS<\/code> need SQL Server 2022 or later; the <code>json<\/code> data type needs SQL Server 2025.<\/em><\/p>\n\n<\/div>\n<\/div> <\/blockquote>\n\n\n\n<h2 id=\"h-why-skipping-json-validation-causes-production-bugs\" class=\"wp-block-heading\">Why skipping JSON validation causes production bugs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Over time, I&#8217;ve encountered various issues with <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/oracle-databases\/json-for-absolute-beginners-part-1-introduction\/\" target=\"_blank\" rel=\"noreferrer noopener\">JSON<\/a> during <a href=\"https:\/\/aws.amazon.com\/what-is\/api\/\" target=\"_blank\" rel=\"noreferrer noopener\">API (application programming interface)<\/a> integration and data processing. Sometimes, a third-party API returns a different format. Other times, some fields are missing. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These problems are usually identified from API errors, <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/theory-and-design\/bad-data-and-dirty-databases\/\" target=\"_blank\" rel=\"noreferrer noopener\">incorrect data<\/a> in the <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/\" target=\"_blank\" rel=\"noreferrer noopener\">database<\/a>, or issues reported by users.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The result? Potential issues later on: <strong>runtime errors, incorrect data<\/strong>, or <strong>production issues<\/strong> that are difficult to debug.<\/p>\n\n\n\n<h2 id=\"h-common-causes-of-bad-json-api-changes-old-code-manual-edits\" class=\"wp-block-heading\">Common causes of bad JSON: API changes, old code, manual edits<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Third-party API changes, old code, and manual database updates are the most common causes of bad JSON in my experience.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When multiple systems are integrated, each system may follow a different <a href=\"https:\/\/www.w3schools.com\/dsa\/dsa_intro.php\" target=\"_blank\" rel=\"noreferrer noopener\">data structure<\/a>, so we shouldn&#8217;t blindly trust the incoming data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The problems I see most often are:<\/p>\n\n\n<div class=\"block-core-list\">\n<ul class=\"wp-block-list\">\n<li>Missing properties<br><br><\/li>\n\n\n\n<li><code><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/empty-thoughts-working-with-null\/\" target=\"_blank\" rel=\"noreferrer noopener\">NULL<\/a><\/code> values where the application expects an object<br><br><\/li>\n\n\n\n<li>Wrong data types, such as a number returned as a <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/find-and-replace-text-in-strings-in-t-sql\/\" target=\"_blank\" rel=\"noreferrer noopener\">string<\/a><br><br><\/li>\n\n\n\n<li>Changes in the JSON structure<br><br><\/li>\n\n\n\n<li>Syntax errors when JSON is edited manually<\/li>\n<\/ul>\n<\/div>\n\n\n<h2 id=\"h-why-json-value-returns-null-instead-of-an-error-in-sql-server\" class=\"wp-block-heading\">Why <code>JSON_VALUE<\/code> returns <code>NULL<\/code> instead of an error in SQL Server<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">One thing to be careful about is <code>JSON_VALUE<\/code> returning <code>NULL<\/code> when a property is missing or its value cannot be extracted in the expected way. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Developers sometimes assume that if the query executes successfully, the JSON is valid. We need to check JSON validity and the expected structure separately.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >DECLARE @j nvarchar(max) = N'{\"Price\":12.5,\"tags\":[\"a\",\"b\"],\"customer\":{\"id\":7}}';\nSELECT JSON_VALUE(@j,'$.Price')    AS exact,          -- 12.5\n       JSON_VALUE(@j,'$.price')    AS wrong_case,     -- NULL (paths are case-sensitive)\n       JSON_VALUE(@j,'$.missing')  AS missing,        -- NULL\n       JSON_VALUE(@j,'$.tags')     AS array_target,   -- NULL (not a scalar)\n       JSON_VALUE(@j,'$.customer') AS object_target;  -- NULL (not a scalar)\n \nSELECT JSON_VALUE(@j,'strict $.price');\n-- Msg 13608: Property cannot be found on the specified JSON path.\nDECLARE @bad1 nvarchar(max) = N'{\"price\":12.5,}';  -- ISJSON = 0\nSELECT JSON_VALUE(@bad1,'$.price');                  -- 12.5, no error\n \nDECLARE @bad3 nvarchar(max) = N'{\"a\":1,,\"price\":5}';\nSELECT JSON_VALUE(@bad3,'$.price');\n-- Msg 13609: JSON text is not properly formatted. Unexpected character '\"' is found at position 8.<\/pre><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">I think this is risky, because <strong>getting the expected value does not mean the complete JSON document is valid. <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >CREATE TABLE #o (id int, payload nvarchar(max));\nINSERT #o VALUES (1, N'{\"price\":10}'),     -- valid\n                 (2, N'{\"price\":20,}'),    -- trailing comma\n                 (3, N'{\"Price\":30}');     -- wrong case\n \nSELECT id, JSON_VALUE(payload,'$.price') AS p FROM #o;\n-- 1 = 10, 2 = 20, 3 = NULL   (no error)\n \nSELECT SUM(CAST(JSON_VALUE(payload,'$.price') AS int)) AS total\nFROM #o WHERE ISJSON(payload) = 1;\n-- 10<\/pre><\/div>\n\n\n\n<h2 id=\"h-how-to-validate-json-in-sql-server-with-isjson-and-check-constraints\" class=\"wp-block-heading\">How to validate JSON in SQL Server with <code>ISJSON<\/code> and <code>CHECK<\/code> constraints<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>TL;DR: To validate JSON in SQL Server, add a <code>CHECK<\/code> constraint that tests <code>ISJSON(payload, OBJECT) = 1<\/code> for syntax and root type, and <code>JSON_PATH_EXISTS<\/code> for required properties.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I would use a <strong><code>CHECK<\/code> constraint with <code>ISJSON<\/code><\/strong> for tables where JSON data integrity is important, since it provides an additional layer of protection <em>even if<\/em> data comes from another application or from direct database queries. <\/p>\n\n\n\n<div id=\"callout-block_99e65c6181f4ac93a99bd026fc17ba47\" class=\"callout alignnone\">\n    <div class=\"child-last:mb-0 child-first:mt-0 bg-gray-50 dark:bg-gray-950 p-4xl my-3xl\">\n\n<p class=\"wp-block-paragraph\"><strong>You may also be interested in&#8230;<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/www.red-gate.com\/simple-talk\/sql\/learn-sql-server\/json-support-in-sql-server-2016\" target=\"_blank\" rel=\"noreferrer noopener\">JSON support in SQL Server 2016 (the complete guide)<\/a><\/p>\n\n<\/div>\n<\/div> \n\n\n<p class=\"wp-block-paragraph\">For high-volume tables, I would first check the performance impact, and then choose the validation strategy based on actual requirements.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >CREATE TABLE dbo.Orders\n(\n    id      int IDENTITY PRIMARY KEY,\n    payload nvarchar(max) NOT NULL\n        CONSTRAINT ck_payload_json  CHECK (ISJSON(payload, OBJECT) = 1),\n        CONSTRAINT ck_payload_price CHECK (JSON_PATH_EXISTS(payload, '$.price') = 1)\n);<\/pre><\/div>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Inserted payload<\/th><th>Result<\/th><\/tr><\/thead><tbody><tr><td><code>{\"price\":20,}<\/code><\/td><td>Msg 547, ck_payload_json<\/td><\/tr><tr><td><code>{\"Price\":30}<\/code><\/td><td>Msg 547, ck_payload_price<\/td><\/tr><tr><td><code>[{\"price\":30}]<\/code><\/td><td>Msg 547, ck_payload_json<\/td><\/tr><tr><td><code>{\"price\":30}<\/code><\/td><td>Inserted<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 id=\"h-should-you-use-the-sql-server-2025-json-data-type\" class=\"wp-block-heading\">Should you use the SQL Server 2025 JSON data type?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">I would <em>consider<\/em> the new JSON data type in SQL Server 2025 for new projects where compatibility isn&#8217;t an issue, but I <strong>wouldn&#8217;t migrate an existing application just because the new type is available. <\/strong><\/p>\n\n\n\n<div id=\"callout-block_99e65c6181f4ac93a99bd026fc17ba47\" class=\"callout alignnone\">\n    <div class=\"child-last:mb-0 child-first:mt-0 bg-gray-50 dark:bg-gray-950 p-4xl my-3xl\">\n\n<p class=\"wp-block-paragraph\"><strong>You may also be interested in&#8230;<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/json-indexing-in-sql-server-2025-how-it-works-and-current-limitations\/\" target=\"_blank\" rel=\"noreferrer noopener\">JSON indexing in SQL Server 2025: how it works and current limitations<\/a><\/p>\n\n<\/div>\n<\/div> \n\n\n<p class=\"wp-block-paragraph\">I would test performance, compatibility, storage and integration with the existing <a href=\"https:\/\/www.red-gate.com\/simple-talk\/development\/how-to-match-names-in-c-without-exact-string-comparisons\/\" target=\"_blank\" rel=\"noreferrer noopener\">C# code<\/a> before making the decision.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >CREATE TABLE dbo.Orders2 (id int IDENTITY PRIMARY KEY, payload json NOT NULL);\nINSERT dbo.Orders2(payload) VALUES (N'{\"price\":20,}');\n-- Msg 13609: JSON text is not properly formatted. Unexpected character '}' is found at position 12.\nINSERT dbo.Orders2(payload) VALUES (N'{\"price\":20, \"b\":  [1,2]}');\nSELECT CAST(payload AS nvarchar(max)), JSON_VALUE(payload,'$.Price') FROM dbo.Orders2;\n-- {\"price\":20,\"b\":[1,2]}   |   NULL<\/pre><\/div>\n\n\n\n<h2 id=\"h-how-much-do-isjson-and-check-constraints-slow-down-inserts\" class=\"wp-block-heading\">How much do <code>ISJSON<\/code> and <code>CHECK<\/code> constraints slow down inserts?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this test, adding an <code>ISJSON CHECK<\/code> constraint made 100,000-row inserts roughly 7\u20138 times slower (about 1.3\u20131.6 seconds versus about 0.2 seconds). Adding <code>JSON_PATH_EXISTS<\/code> pushed that to roughly 11\u201312 times. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Meanwhile, the <code>json<\/code> data type was about 11 times slower than an unchecked column &#8211; but used 31% less storage.<\/p>\n\n\n\n<h3 id=\"h-the-test\" class=\"wp-block-heading\">The test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">100,000 rows of about 350 characters each, inserted into <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/temporary-tables-in-sql-server\/\" target=\"_blank\" rel=\"noreferrer noopener\">temp tables<\/a> on SQL Server 2025 Express on a desktop machine. Each result is the average of 5 runs, and the whole test was run twice.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Table definition<\/th><th>Run 1 avg<\/th><th>Run 2 avg<\/th><th>Approx. slowdown vs no check<\/th><\/tr><\/thead><tbody><tr><td><code>nvarchar(max)<\/code>, no check<\/td><td>201 ms<\/td><td>192 ms<\/td><td>1\u00d7<\/td><\/tr><tr><td>+ <code>CHECK ISJSON(payload, OBJECT) = 1<\/code><\/td><td>1,585 ms<\/td><td>1,349 ms<\/td><td>~7.5\u00d7<\/td><\/tr><tr><td>+ ISJSON and <code>JSON_PATH_EXISTS($.customer.id)<\/code><\/td><td>2,489 ms<\/td><td>2,167 ms<\/td><td>~11.8\u00d7<\/td><\/tr><tr><td><code>json<\/code> data type (2025)<\/td><td>2,456 ms<\/td><td>1,995 ms<\/td><td>~11.3\u00d7<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Storage for the same 100,000 documents: <strong>68,706 KB as <code>nvarchar(max)<\/code><\/strong>, <strong>47,558 KB as <code>json<\/code><\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What does the test show?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test shows that <strong>how much <code>ISJSON<\/code> and <code>CHECK<\/code> constraints slow down inserts really depends on the application and the workload.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For critical business data and integration payloads, I think data integrity is more important than saving a few milliseconds. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For high-volume logging or temporary data, however, I&#8217;d benchmark the actual workload and choose the right approach that way. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s also recommended to avoid unnecessary repeated validation.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >SELECT TOP (100000) CONCAT(N'{\"id\":', ROW_NUMBER() OVER (ORDER BY (SELECT 1)),\n       N',\"customer\":{\"id\":', ABS(CHECKSUM(NEWID())) % 1000,\n       N'},\"items\":[{\"sku\":\"A-1\",\"qty\":2,\"price\":9.99}],\"note\":\"', REPLICATE(N'x',200), N'\"}') AS p\nINTO #src FROM sys.all_objects a CROSS JOIN sys.all_objects b;\n \nCREATE TABLE #n  (payload nvarchar(max) NOT NULL);\nCREATE TABLE #c  (payload nvarchar(max) NOT NULL CHECK (ISJSON(payload, OBJECT) = 1));\nCREATE TABLE #c2 (payload nvarchar(max) NOT NULL\n                  CHECK (ISJSON(payload, OBJECT) = 1 AND JSON_PATH_EXISTS(payload,'$.customer.id') = 1));\nCREATE TABLE #t  (payload json NOT NULL);   -- SQL Server 2025 only\n \nDECLARE @t0 datetime2 = SYSDATETIME();\nINSERT #n SELECT p FROM #src;  PRINT CONCAT('no check: ', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms');\nSET @t0 = SYSDATETIME();\nINSERT #c SELECT p FROM #src;  PRINT CONCAT('ISJSON:   ', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms');\nSET @t0 = SYSDATETIME();\nINSERT #c2 SELECT p FROM #src; PRINT CONCAT('+ path:   ', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms');\nSET @t0 = SYSDATETIME();\nINSERT #t SELECT p FROM #src;  PRINT CONCAT('json type:', DATEDIFF(ms, @t0, SYSDATETIME()), ' ms');<\/pre><\/div>\n\n\n\n<section id=\"my-first-block-block_74015c12d73307a440807140cd6ba775\" class=\"my-first-block alignwide\">\n    <div class=\"bg-brand-600 text-base-white py-5xl px-4xl rounded-sm bg-gradient-to-r from-brand-600 to-brand-500 red\">\n        <div class=\"gap-4xl items-start md:items-center flex flex-col md:flex-row justify-between\">\n            <div class=\"flex-1 col-span-10 lg:col-span-7\">\n                <h3 class=\"mt-0 font-display mb-2 text-display-sm\">Automated and controlled preparation of test databases<\/h3>\n                <div class=\"child:last-of-type:mb-0\">\n                                            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.                                    <\/div>\n            <\/div>\n                                            <a href=\"https:\/\/www.red-gate.com\/products\/flyway\/enterprise\/\" class=\"btn btn--secondary btn--lg\" aria-label=\"Learn more &amp; try for free: Automated and controlled preparation of test databases\">Learn more &amp; try for free<\/a>\n                    <\/div>\n    <\/div>\n<\/section>\n\n\n<h2 id=\"h-how-to-validate-json-in-c-with-system-text-json-before-inserting\" class=\"wp-block-heading\">How to validate JSON in C# with <code>System.Text.Json<\/code> before inserting<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>TL;DR: To validate JSON in C#, parse it with <code>JsonDocument.Parse<\/code> (with trailing commas and comments disallowed), then check the root type, required properties and value types before sending it to SQL Server.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I prefer validating JSON in C# before sending it to the database. I usually use <code>System.Text.Json<\/code> to parse the payload and <strong>validate the expected structure and data types<\/strong>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For strongly typed APIs, I prefer <a href=\"https:\/\/en.wikipedia.org\/wiki\/Data_transfer_object\" target=\"_blank\" rel=\"noreferrer noopener\">DTOs<\/a> with proper validation. <a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/validation-verification-modification\/\" target=\"_blank\" rel=\"noreferrer noopener\">Database validation<\/a> is still important as an additional layer of protection.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >using System.Text.Json;\n \nstatic string? ValidateOrder(string json)\n{\n    try\n    {\n        using var doc = JsonDocument.Parse(json, new JsonDocumentOptions\n        {\n            AllowTrailingCommas = false,\n            CommentHandling = JsonCommentHandling.Disallow,\n            MaxDepth = 32\n        });\n        var root = doc.RootElement;\n        if (root.ValueKind != JsonValueKind.Object) return \"Root must be a JSON object.\";\n        if (!root.TryGetProperty(\"price\", out var price))\n            return \"Missing required property 'price'.\";\n        if (price.ValueKind != JsonValueKind.Number)\n            return $\"'price' must be a number, got {price.ValueKind}.\";\n        if (!price.TryGetDecimal(out var p) || p &lt; 0)\n            return \"'price' must be a non-negative decimal.\";\n        return null;   \/\/ valid\n    }\n    catch (JsonException ex)\n    {\n        return $\"Malformed JSON at line {ex.LineNumber}, byte {ex.BytePositionInLine}: {ex.Message}\";\n    }\n}<\/pre><\/div>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Input<\/th><th>ValidateOrder result<\/th><\/tr><\/thead><tbody><tr><td><code>{\"price\":12.5}<\/code><\/td><td><code>null<\/code> (valid)<\/td><\/tr><tr><td><code>{\"price\":20,}<\/code><\/td><td>Malformed JSON at line 0, byte 12: \u2026<\/td><\/tr><tr><td><code>{\"Price\":30}<\/code><\/td><td>Missing required property \u2018price\u2019.<\/td><\/tr><tr><td><code>{\"price\":\"12,50\"}<\/code><\/td><td>\u2018price\u2019 must be a number, got String.<\/td><\/tr><tr><td><code>[{\"price\":1}]<\/code><\/td><td>Root must be a JSON object.<\/td><\/tr><tr><td><code>{\"price\":-3}<\/code><\/td><td>\u2018price\u2019 must be a non-negative decimal.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 id=\"h-how-sql-server-and-net-handle-duplicate-json-keys\" class=\"wp-block-heading\">How SQL Server and .NET handle duplicate JSON keys<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Duplicate keys are valid as far as <code>ISJSON<\/code> is concerned, but parsers disagree on which value wins. The examples below show SQL Server and .NET 8 giving different answers. <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I would <strong>reject duplicate keys in important payloads<\/strong> instead of depending on parser behavior.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >-- SQL Server\nSELECT ISJSON(N'{\"a\":1,\"a\":2}');            -- 1 (valid)\nSELECT JSON_VALUE(N'{\"a\":1,\"a\":2}','$.a');  -- 1\n \n\/\/ .NET 8\nusing var d = JsonDocument.Parse(\"{\\\"a\\\":1,\\\"a\\\":2}\");\nd.RootElement.GetProperty(\"a\");             \/\/ 2\n \nJsonNode.Parse(\"{\\\"a\\\":1,\\\"a\\\":2}\")!.AsObject();\n\/\/ ArgumentException: An item with the same key has already been added. Key: a<\/pre><\/div>\n\n\n\n<h2 id=\"h-how-to-debug-a-failed-json-payload-in-sql-server-and-c\" class=\"wp-block-heading\">How to debug a failed JSON payload in SQL Server and C#<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If it&#8217;s related to SQL Server, I check <code>ISJSON<\/code>, the JSON paths, and the <code>JSON_VALUE<\/code> and <code>OPENJSON<\/code> results. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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:<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tsql decode:true \" >SELECT id FROM dbo.Orders WHERE ISJSON(payload) = 0 OR payload IS NULL;  -- ISJSON(NULL) is NULL, not 0<\/pre><\/div>\n\n\n\n<h3 id=\"h-how-to-debug-a-failed-json-payload-in-sql-server-and-c-in-summary\" class=\"wp-block-heading\">How to debug a failed JSON payload in SQL Server and C# (in summary)<\/h3>\n\n\n<div class=\"block-core-list\">\n<ol class=\"wp-block-list\">\n<li>Capture the exact JSON payload that failed and compare it with the expected structure.<br><br><\/li>\n\n\n\n<li>Reproduce the issue with the same data.<br><br><\/li>\n\n\n\n<li>Validate the payload with the C# parser (<code>JsonDocument.Parse<\/code>) to see whether it\u2019s malformed or just structurally wrong.<br><br><\/li>\n\n\n\n<li>If it looks SQL Server-related, check <code>ISJSON<\/code>, the JSON paths, and the <code>JSON_VALUE<\/code> and <code>OPENJSON<\/code> results.<br><br><\/li>\n\n\n\n<li>Check the application logs and the actual data types to identify the root cause.<\/li>\n<\/ol>\n<\/div>\n\n\n<h2 id=\"h-should-you-validate-json-in-the-app-the-database-or-both\" class=\"wp-block-heading\">Should you validate JSON in the app, the database, or both?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>I would recommend validating at both levels<\/strong>. The application should validate the structure, required fields, data types and business rules before processing the payload &#8211; and the database should enforce important data integrity rules wherever possible. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We should not depend only on application-level validation, because data can enter the database through other applications or scripts.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Problem<\/th><th>ISJSON CHECK<\/th><th>JSON_PATH_EXISTS CHECK<\/th><th>json type (2025)<\/th><th>C# System.Text.Json<\/th><\/tr><\/thead><tbody><tr><td>Trailing comma \/ malformed syntax<\/td><td>Caught<\/td><td>n\/a (use <code>ISJSON<\/code> as well)<\/td><td>Rejected (Msg 13609)<\/td><td>Caught (<code>AllowTrailingCommas = false<\/code>)<\/td><\/tr><tr><td>Root isn\u2019t an object<\/td><td>Caught (<code>OBJECT<\/code>)<\/td><td>n\/a<\/td><td>Not caught<\/td><td>Caught (<code>ValueKind<\/code> check)<\/td><\/tr><tr><td>Missing or wrong-case property<\/td><td>Not caught<\/td><td>Caught<\/td><td>Not caught (<code>JSON_VALUE<\/code> returns <code>NULL<\/code>)<\/td><td>Caught<\/td><\/tr><tr><td>Wrong data type (<code>\"12,50\"<\/code> as a string)<\/td><td>Not caught<\/td><td>Not caught<\/td><td>Not caught<\/td><td>Caught<\/td><\/tr><tr><td>Duplicate keys<\/td><td>Not caught<\/td><td>Not caught<\/td><td>Not tested here<\/td><td>Parser-dependent (<code>JsonDocument<\/code> accepts, <code>JsonNode<\/code> throws)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">My three rules would be:<\/p>\n\n\n<div class=\"block-core-list\">\n<ul class=\"wp-block-list\">\n<li><strong>Never blindly trust JSON<\/strong>, even if it comes from your own application or a trusted API.<br><br><\/li>\n\n\n\n<li><strong>Validate the structure, data types, required fields and duplicate keys<\/strong> where they matter.<br><br><\/li>\n\n\n\n<li><strong>Test performance and edge cases with real payloads<\/strong> before making changes in production.<\/li>\n<\/ul>\n<\/div>\n\n\n<div id=\"callout-block_99e65c6181f4ac93a99bd026fc17ba47\" class=\"callout alignnone\">\n    <div class=\"child-last:mb-0 child-first:mt-0 bg-gray-50 dark:bg-gray-950 p-4xl my-3xl\">\n\n<p class=\"wp-block-paragraph\"><strong>You may also be interested in&#8230;<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/www.red-gate.com\/simple-talk\/databases\/sql-server\/t-sql-programming-sql-server\/techniques-to-query-azure-sqls-new-json-datatype\/\" target=\"_blank\" rel=\"noreferrer noopener\">Azure SQL Native JSON Data Type: Query Techniques<\/a><\/p>\n\n<\/div>\n<\/div> \n\n\n<h2 id=\"h-conclusion-valid-json-isn-t-the-same-as-valid-business-data\" class=\"wp-block-heading\">Conclusion: valid JSON isn&#8217;t the same as valid business data<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The main thing I want readers to remember is that <strong>valid JSON does not always mean valid business data<\/strong>. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<section id=\"faq\" class=\"faq-block my-5xl\">\n    <h2>FAQs: JSON validation in SQL Server<\/h2>\n\n            <h3 class=\"mt-4xl\">1. Does ISJSON catch every JSON problem in SQL Server?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">No. <code>ISJSON<\/code> 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: <code>ISJSON<\/code> returns 1 for <code dir=\"ltr\">{\"a\":1,\"a\":2}<\/code>. Combine it with <code>JSON_PATH_EXISTS<\/code> in a <code>CHECK<\/code> constraint, or validate structure in application code, for fuller coverage.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">2. Why does JSON_VALUE return NULL instead of an error?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">In the default lax mode, <code>JSON_VALUE<\/code> returns <code>NULL<\/code> when a property is missing, the key\u2019s case doesn\u2019t match, or the target is an array or object rather than a scalar. Add the strict keyword to the path, for example <code dir=\"ltr\">'strict $.price'<\/code>, and SQL Server raises error 13608 for a missing property <em>instead<\/em> of returning <code>NULL<\/code>.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">3. Should I use a CHECK constraint or the json data type to validate JSON?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">On versions before SQL Server 2025, use a <code>CHECK<\/code> constraint with <code>ISJSON<\/code> on an <code>nvarchar(max)<\/code> column. SQL Server 2025\u2019s <code>json<\/code> 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.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">4. How do I find invalid JSON already stored in a SQL Server table?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">Query for rows where <code dir=\"ltr\">ISJSON(payload) = 0 OR payload IS NULL<\/code>. The <code>NULL<\/code> check matters because <code>ISJSON(NULL)<\/code> returns <code>NULL<\/code> rather than 0, so a plain <code dir=\"ltr\">ISJSON(payload) = 0<\/code> filter misses <code>NULL<\/code> values. Run it before adding a <code>CHECK<\/code> constraint to an existing table, because existing invalid rows will make the constraint fail.<\/p>\n        <\/div>\n            <h3 class=\"mt-4xl\">5. Why do duplicate keys in JSON cause problems?<\/h3>\n        <div class=\"faq-answer\">\n            <p dir=\"ltr\">Parsers disagree on duplicate keys. In the tests above, SQL Server treated <code dir=\"ltr\">{\"a\":1,\"a\":2}<\/code> as valid and <code>JSON_VALUE<\/code> returned the first value (1), while .NET 8\u2019s <code>JsonDocument<\/code> returned the last (2) and <code>JsonNode.Parse<\/code> threw an exception. Two systems can therefore read different values from the same payload, so reject duplicate keys in important payloads.<\/p>\n        <\/div>\n    <\/section>\n\n\n\n<section id=\"my-first-block-block_3decb4eb8f8a4dd2b300e5af754df435\" class=\"my-first-block alignwide\">\n    <div class=\"bg-brand-600 text-base-white py-5xl px-4xl rounded-sm bg-gradient-to-r from-brand-600 to-brand-500 red\">\n        <div class=\"gap-4xl items-start md:items-center flex flex-col md:flex-row justify-between\">\n            <div class=\"flex-1 col-span-10 lg:col-span-7\">\n                <h3 class=\"mt-0 font-display mb-2 text-display-sm\">Subscribe to the Simple Talk newsletter<\/h3>\n                <div class=\"child:last-of-type:mb-0\">\n                                            All the latest articles, guides, podcasts, and more &#8211; delivered straight to your inbox.                                    <\/div>\n            <\/div>\n                                            <a href=\"https:\/\/www.red-gate.com\/simple-talk\/subscribe\/\" class=\"btn btn--secondary btn--lg\" aria-label=\"Subscribe now: Subscribe to the Simple Talk newsletter\">Subscribe now<\/a>\n                    <\/div>\n    <\/div>\n<\/section>","protected":false},"excerpt":{"rendered":"<p>Valid JSON isn&#8217;t always valid data. Learn how ISJSON, CHECK constraints and System.Text.Json catch bad payloads in SQL Server, with insert benchmarks.&hellip;<\/p>\n","protected":false},"author":347307,"featured_media":107923,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538,143523,143526,53,143524],"tags":[4143,4371,4168,4170,4150,4151],"coauthors":[159419],"class_list":["post-113998","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dotnet-development","category-databases","category-development","category-featured","category-sql-server","tag-net","tag-c","tag-database","tag-database-administration","tag-sql","tag-sql-server"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/113998","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/347307"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=113998"}],"version-history":[{"count":17,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/113998\/revisions"}],"predecessor-version":[{"id":114601,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/113998\/revisions\/114601"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media\/107923"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=113998"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=113998"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=113998"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=113998"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}