Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsiTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
When an API rejects JSON, the cause is usually a small difference between strict JSON and the JavaScript-like object notation that looks familiar in application code. The reliable fix is to inspect the exact request or response body, find the first point where it stops matching JSON syntax, and correct the payload—not to make the parser more permissive. These six common errors cover malformed punctuation, quoting, unsupported syntax, string escaping, invalid values, and extra or ambiguous data.
A parser’s error location is a useful clue, but it may point to where parsing became impossible rather than to the original typo. Capture the bytes actually sent or received, validate them with a strict JSON parser, and then check that the valid JSON also meets the API’s contract.
What should I check first when an API says the JSON is invalid?
Start with the raw body on the wire, not just the object or string in your source code. The application may transform a value while serializing it, or a server, framework, proxy, or client may add content that is not visible in the object you intended to send.
Free tools Windows power users keep installed
One-click scans. No signup required.
- Capture the exact request or response body. Include the surrounding context and preserve invisible characters where possible. For a response, also note the HTTP status and content type; inspect server logs if the body contains an error or unexpected output. Avoid exposing credentials, personal data, or other secrets in logs.
- Run the captured body through a strict JSON parser. Record the first reported line and column, byte offset, or unexpected token. The reported position is where the parser could no longer continue, not necessarily where the defect began.
- Inspect the characters immediately before the reported position. Check commas, colons, braces, brackets, and quotation marks. A missing separator can make a later, otherwise valid token appear to be the problem.
- Look for JavaScript-only syntax, invalid escapes, and invalid numbers. Search for single-quoted strings, unquoted names, trailing commas, comments,
undefined,NaN,Infinity, incomplete exponents, and unescaped control characters. - Check for duplicate names and extra bytes. A document can parse but still be ambiguous to different consumers, or valid JSON can be followed by unrelated text.
- Replace manual JSON string assembly with a serializer. After syntax validation, validate the data against the API’s schema or contract, then add an automated check so the same failure is caught before deployment.
This order helps separate three different problems: invalid JSON syntax, valid JSON that violates the API contract, and a request or response whose actual bytes differ from what the application intended.
Popular on Amazon
- 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
- 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
- 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
- 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
- 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
When inspecting a failure, distinguish the body from the transport details around it. The declared content type and encoding should make sense for what the client actually received; a mismatch can complicate diagnosis even when the body looks plausible in a log or console. If a parser reports an unexpected token at the beginning, first confirm that the body really starts with JSON rather than an error page or other response content. If it reports a problem at the end, check for appended non-whitespace text before rewriting valid fields.
Choose tools that give useful diagnostics—such as a line, column, byte offset, or unexpected token—and make sure they validate strict JSON rather than silently accepting extensions. A quick local parse is helpful, but it should use the same captured payload that failed at the API boundary. A source object displayed by a debugger is not a substitute for that evidence.
1. What if the JSON has a missing comma, colon, or bracket?
JSON’s structure depends on exact punctuation: objects use curly braces, arrays use square brackets, names are separated from values by colons, and members or elements are separated by commas. A missing separator or unmatched delimiter makes the document impossible to parse.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →For example, this object is missing a comma between the value 42 and the next property:
{"user":{"id":42 "active":true}}
The corrected version is:
{"user":{"id":42,"active":true}}
The parser may not identify the missing comma directly. It may instead flag "active", because that is where the parser can no longer interpret the sequence it has received. When a token looks valid on its own, inspect the punctuation just before it.
How to find a nesting or punctuation mistake
- Pair each opening
{with a closing}, and each opening[with a closing]. - Check that each object property has a colon between its quoted name and value.
- Check that adjacent properties or array elements have commas between them.
- Check that the comma is between items, not after the last item.
Nested data is especially easy to break when JSON is assembled by concatenating text. Generate the document from the source object with the language’s JSON serializer, then capture the actual request body when debugging an API. Logging only the source object does not show whether the final serialized payload is malformed.
2. Why do single quotes or unquoted property names fail?
Strict JSON requires double quotes around strings and property names. A JavaScript object literal can use forms that JSON cannot, so an object that works as code is not necessarily a valid JSON document.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →This is a JavaScript-style object literal, not strict JSON:
Also popular on Amazon
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
{'user': 'Ada'}
In JSON, both the property name and string value use double quotes:
{"user":"Ada"}
Keep the host language’s string delimiters separate from the JSON document’s delimiters. For example, JavaScript can hold JSON text in a single-quoted string while the text inside that string remains valid JSON:
JSON.parse('{"user":"Ada"}')
The same distinction matters in shell commands, templates, and HTTP client configuration. An outer quote used to pass a value to a tool does not change the rules for the JSON inside it. If a parser complains at the start of a property or value, check whether the JSON text uses single quotes or leaves a property name unquoted.
3. Are trailing commas, comments, and JavaScript syntax valid JSON?
No. Standard JSON does not permit trailing commas, comments, undefined, functions, or other JavaScript object-literal conveniences. A permissive parser may accept some extensions, but another API client or server may reject them.
For example, the comma after the final member makes this invalid:
{"user":"Ada",}
Remove the trailing comma:
{"user":"Ada"}
Do not assume that a document is interoperable just because one parser accepts it. Some libraries offer modes that allow extensions such as comments, trailing commas, or quoted numbers. That can be convenient locally, but it does not make those extensions part of standard JSON or guarantee that other consumers will handle them the same way.
For API payloads, validate with a strict parser and remove non-standard syntax rather than changing the receiving parser to accept it. If a value is absent, represent it according to the API contract; do not substitute a JavaScript-only value such as undefined.
This is a practical tradeoff between local convenience and interoperability. A permissive mode can help when working with a configuration format that intentionally allows extensions, but an API exchange needs predictable behavior across languages, clients, servers, and intermediaries. If one side accepts a comment or trailing comma while another rejects it, the same payload can appear to work in one test and fail in production. Prefer strict validation at the boundary and reserve extension-tolerant parsing for cases where every consumer explicitly supports the same format.
Also popular on Amazon
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
4. How do I fix invalid JSON string escaping?
Inside a JSON string, quotation marks and backslashes must be escaped, and control characters such as an actual line feed, carriage return, or tab must be represented with JSON escapes. A malformed or unclosed string can make the rest of the payload appear invalid.
In this example, the quotation marks around hello prematurely end the JSON string:
{"message":"She said "hello""}
Escape the inner quotation marks:
{"message":"She said "hello""}
A JSON escape is not interchangeable with every escape a programming language happens to support. For instance, x20 is not a valid JSON escape. JSON supports u followed by exactly four hexadecimal digits for that escape form. A backslash that begins an unsupported or incomplete escape can invalidate the containing string.
What to inspect in a failing string
- Check whether every string has a closing double quote.
- Escape quotation marks inside the string and backslashes that are part of its content.
- Look for actual line breaks, carriage returns, or tabs inside the string; encode them as
n,r, ort. - Check each backslash escape against JSON’s rules instead of assuming the host language’s escape syntax applies.
Manually escaping nested strings is error-prone. A serializer can encode string content correctly, while a strict parser applied to the final payload can confirm that the resulting document is valid.
When a message contains several layers of quoting—for example, JSON text inside a programming-language string—each layer has its own escaping rules. Fixing only the outer string may leave the JSON text invalid, and adding extra backslashes by guesswork can create a different malformed escape. Inspect the final serialized body rather than relying on how the source literal is displayed.
5. Which JSON numbers and values are invalid?
JSON’s number grammar is narrower than the numeric syntax some programming languages accept. A number cannot have a leading zero, a decimal point without digits after it, or an incomplete exponent. Values such as NaN, Infinity, -Infinity, and undefined are not JSON values.
These examples are invalid:
{"count":01}
{"ratio":1.}
{"value":1e}
Use valid JSON numbers instead:
{"count":1,"ratio":1.0,"value":1e3}
When an application has a non-finite number or a missing value, decide how the API contract represents it. A contract might specify null or a string with explicit meaning, but those are not interchangeable choices: the API’s expected semantics should determine which representation to use. Serialize consistently and validate the output rather than relying on a parser to interpret a programming-language value that JSON does not define.
Recommended Free Tools
Do not treat a syntactically valid substitute as automatically correct for the API. Replacing a missing value with null, for example, is appropriate only if the contract gives null that meaning; a string such as "Infinity" is likewise a deliberate text value, not a numeric infinity. Make the representation explicit at the point where application data is converted to JSON, then test that the receiving API expects the same thing.
Also popular on Amazon
- Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
- Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
- 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
- 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
- Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
6. Can duplicate keys or text after the JSON value break an API?
Yes. Duplicate object names can create different results across implementations even when a parser accepts the document. Extra non-whitespace content after a JSON value can also cause parsing to fail, despite the JSON portion itself being valid.
For example, an object with two values for the same name is ambiguous:
{"role":"user","role":"admin"}
RFC 8259 says that names within an object SHOULD be unique. Implementations may keep the first value, keep the last, combine values, or reject the object. Treat duplicate names as a generation or validation error rather than depending on one consumer’s behavior.
A separate issue is a valid object followed by unrelated text:
{"ok":true}unexpected text
A parser can report unexpected non-whitespace after the JSON data. In an API response, inspect the raw body for an HTML error page, framework warning, debug output, proxy-added content, or concatenated response. Check the HTTP status, content type, and server logs before changing application parsing. If the response is unexpectedly not JSON, the underlying problem may be an error response or intermediary behavior rather than the JSON parser itself.
These problems call for different checks. Duplicate names require examining how the object was generated and adding uniqueness detection; appended bytes require inspecting the full response boundary and the systems that produced or forwarded it. A parser that accepts duplicate names does not prove that every consumer will interpret them consistently, while a parser that rejects trailing content is correctly warning that the whole body is not a single JSON value.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.How can I prevent JSON parsing failures in production?
Use serializer-generated payloads, validate the exact bytes that cross the API boundary, and add contract checks after syntax checks. These measures address different failure points: serialization prevents many formatting mistakes, raw-body inspection exposes transport or response changes, and schema validation catches well-formed JSON that does not meet the API’s requirements.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteBuild a reliable validation path
- Serialize structured data. Use the JSON facilities in the language or library that constructs the request. Avoid building nested JSON with string concatenation.
- Validate syntax strictly. Do not rely on parser modes that accept comments, trailing commas, or other non-standard extensions when the payload must work across API consumers.
- Validate the API contract. Syntax validation only answers whether the bytes form JSON. Schema or contract validation can catch missing required data, incorrect types, or other API-specific violations.
- Check duplicate names. Make uniqueness part of generation or validation so behavior does not depend on which duplicate-key policy a consumer uses.
- Test request and response boundaries. Confirm the serialized request body and inspect representative raw responses, including error responses. Check status and content type alongside the body.
- Log safely. Preserve enough information to diagnose malformed payloads, but redact secrets and sensitive values. Operational visibility is useful only if it does not expose data that should not be retained.
What the parser error can and cannot tell you
A syntax error narrows the search to a location, but it is not a definitive diagnosis of the original mistake. A missing comma can cause the parser to complain at the next property; a malformed escape can make an entire string unreadable; and extra response text can make otherwise valid JSON fail only at the end. Compare the reported position with the raw body and inspect the surrounding characters before changing later fields.
Also popular on Amazon
- 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
- 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
- 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
- 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
- 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
Also keep syntax and meaning separate. A payload can be valid JSON yet still use the wrong field type or omit a required property for the API. Conversely, a schema validator cannot repair bytes that are not valid JSON. Run syntax validation first, then contract validation.
There is no single best debugging tool for every stage. A strict parser is the right first check for syntax and should make the failure location clear; a formatter can make nested structure easier to inspect; duplicate-key detection catches an interoperability hazard that a basic successful parse may miss; and schema validation checks API-specific requirements. An API testing tool or request inspector can help you examine the exact body and response metadata, but protect sensitive values when capturing or sharing logs. These checks complement one another rather than replacing the serializer that prevents hand-built JSON errors in the first place.
For an automated regression check, exercise the serialization boundary with representative structured data, parse the generated output strictly, and validate it against the contract. Include cases likely to stress strings and values—such as embedded quotes, backslashes, line breaks, missing values, and non-finite numbers—so the code’s actual serialization decisions are tested. At the API boundary, inspect both successful and error responses; unexpected HTML or diagnostic text often appears on an error path that ordinary success tests do not cover.
Which JSON error is most likely when parsing fails?
Use the location and shape of the failure as clues, not as proof. A report near a property name often warrants checking the preceding comma or quote; a failure inside a string points toward escaping; and a complaint after an apparently complete value can indicate extra response bytes.
- Near a second property or array element: inspect the separator before it and the surrounding brackets or braces.
- At the start of a key or string: check for single quotes, an unquoted name, or an earlier string that did not close.
- Near the end of a value: check for a trailing comma, incomplete number, or invalid escape.
- After a complete object or array: inspect for non-whitespace bytes appended to the body.
- No syntax error, but the API still rejects the payload: validate the JSON against the API contract and check the request’s status, content type, and actual body.
The first reported token is where the parser detected a problem, not necessarily where the defect began. Rechecking the immediately preceding punctuation and capturing the actual wire payload are often more useful than repeatedly editing the field named by the error.
Frequently Asked Questions
Why does JSON.parse say unexpected token?
It means the supplied text does not conform to JSON grammar at the point the parser can no longer continue. The reported token may be downstream of the original mistake, such as a missing comma before a later property.
Why does JSON work in my JavaScript code but fail in an API request?
The code may be a valid JavaScript object literal without being valid JSON: single quotes, unquoted property names, trailing commas, and values such as undefined are examples. Inspect the serialized request body rather than assuming the source object and transmitted text are identical.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Can an API return invalid JSON even when my server generated a JSON object?
Yes. The response body can include framework warnings, an HTML error page, proxy-added text, or other bytes around the JSON value. Compare the raw body with the HTTP status and content type to distinguish a formatting problem from an unexpected response.
Is a JSON validator enough to prove an API payload is correct?
No. A syntax validator confirms that the body is parseable JSON, but it does not establish that required fields, types, or values match a particular API contract. Use contract or schema validation after syntax validation.
Why does my JSON have invalid quotes, commas, or brackets?
Strict JSON requires double-quoted strings and property names, commas between members or elements, colons between names and values, and matching braces and brackets. Check the punctuation immediately before the parser’s reported location; the defect may be earlier than the token it flags.
What should I do if valid JSON still gets rejected by an API?
Check the API contract or schema for required fields and expected types, then inspect the exact request body, HTTP status, content type, and response. A syntax validator confirms grammar, not API-specific meaning or whether the transmitted bytes match the intended payload.

