25 JSON Mistakes Every Developer Makes
JSON is the backbone of web communication. It is lightweight and easy to read. However, its rules are strict. Small errors break your code.
Avoid these common mistakes to write better data structures.
Syntax Errors
- Use double quotes only. Single quotes work in JavaScript but fail in JSON.
- Remove trailing commas. A comma after the last item causes a crash.
- Add missing commas. Every key-value pair needs a comma between them.
- Quote all keys. Every key must have double quotes around it.
- Match your brackets. Do not use curly braces where square brackets belong.
Data Type Mistakes
- Handle undefined values. JSON does not support undefined. Use null instead.
- Avoid NaN and Infinity. These values turn into null during serialization.
- Remember Date formats. JSON treats dates as strings. You must parse them back to Date objects.
- Use base-10 numbers. Do not use hex or octal formats.
- Do not store functions. JSON is for static data only.
- Avoid comments. JSON does not allow // or /* */ comments.
- Escape double quotes. Use a backslash to include quotes inside a string.
- Use \n for newlines. You cannot hit enter inside a string value.
- Escape backslashes. Use \ for paths or regex patterns.
Environment and Logic Errors
- Check your input. Do not pass an object to JSON.parse().
- Watch your casing. "userId" and "userid" are different keys.
- Do not rely on order. JSON does not guarantee the sequence of keys.
- Never use eval(). Use JSON.parse() to prevent security risks.
- Protect large numbers. Pass 64-bit IDs as strings to avoid precision loss.
- Use try...catch blocks. Invalid JSON will crash your app if you do not catch errors.
- Fix circular references. You cannot stringify an object that points back to itself.
- Know the difference. JSON is more restrictive than a standard JavaScript object.
- Avoid empty strings. Use {} or [] instead of "".
How to stay safe:
- Use a validator to check your syntax.
- Use Prettier in your editor to auto-format files.
- Always wrap parsing logic in a try...catch block.
Source: https://dev.to/jsdevspace/25-json-mistakes-every-developer-makes-36e6
