Back to articles
Why Your JSON Is Probably Invalid (And How to Fix It)

Why Your JSON Is Probably Invalid (And How to Fix It)

via Dev.to TutorialMichael Lip

I've code-reviewed hundreds of pull requests that include JSON configuration files, API responses, or fixture data. The number of times I've seen technically invalid JSON that "works" because the parser is lenient is staggering. Here are the seven mistakes I see most often, why they're wrong according to the spec, and how to fix them. 1. Trailing commas This is by far the most common offender. { "name" : "Michael" , "age" : 30 , } That trailing comma after 30 is invalid JSON. JavaScript objects allow it. Python dicts allow it. JSON does not. The spec (RFC 8259) explicitly requires that the comma only appear between values, not after the last one. Every major browser's JSON.parse() will throw a SyntaxError on this. The reason you might not notice is that many config file parsers — VS Code's settings.json parser, for example — use a superset called JSON5 or JSONC that tolerates trailing commas. But if you're sending this over an API or feeding it into a strict parser, it breaks. 2. Singl

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles