Explain Codes LogoExplain Codes Logo

Error "Uncaught SyntaxError: Unexpected token with JSON.parse"

javascript
json-parse
error-handling
debugging
Anton ShumikhinbyAnton Shumikhin·Feb 6, 2025
TLDR

The SyntaxError in JSON.parse() often rears its head due to incorrect JSON syntax. Here's your talisman:

  • Favor the " for string values.
  • Shun commas after the last object or element like a vampire avoids sunlight.
  • Embrace keys securely in ".

Metaphors aside, here's the practical stuff:

let json = '{"valid": true}'; // Correctly formatted JSON try { let obj = JSON.parse(json); // Try parsing the JSON string console.log(obj); // If there's no error, this will display the object } catch (e) { console.error("JSON Error:", e); // Oops, the JSON tripped }

Your JSON ought to mirror the above structure. This should keep errors at bay during parsing.

Dissecting the JSON.parse conundrum

Checking data types before parsing

Absolute rule no.1: JSON.parse needs a string to feast on. It doesn't like to chew on an actual JavaScript object or array; access the properties directly like a civilized coder.

let products = [{ name: "Wooden Stake", price: 19.99, quantity: 1 }]; // No parsing required console.log(products[0].price); // Outputs: 19.99 (BTW, that's a pricey stake!)

Rule no.2: If you've got trust issues and are skeptical if products is a string or an object, just ask politely:

console.log(typeof products); // "please tell me your type, kind object"

Avoid invalid JSON conversion

Newton's law of JSON: Never apply .toString() on an object, intending to feed it to JSON.parse. It results in [object Object], which is the JSON equivalent of a garlic bread (read: it's invalid).

let obj = { a: 1 }; let str = JSON.stringify(obj); // Proper way to convert object to string console.log(str); // Outputs: '{"a":1}'

Watch out for loose cannons a.k.a special characters

Yes, special characters are like vampires hidden in strings. Make sure they are escaped before you start parsing your JSON.

let problematicJson = '{"text": "He said, \"Hello\"."}'; let correctedJson = problematicJson.replace(/\\/g, "\\\\"); let obj = JSON.parse(correctedJson); console.log(obj.text); // Bam! The quote-loving string

Don't mess with numeric data

Please ensure that numeric data (like price tags) are actual numbers, not strings. You wouldn't want to buy a stake shopping online and instead get a stake emoji, would you?

let productsStr = '[{ "name": "Garlic", "price": "1.25", "quantity": "20" }]'; let products = JSON.parse(productsStr).map(p => ({ ...p, price: parseFloat(p.price), quantity: parseInt(p.quantity, 10) })); console.log(products[0].price); // Outputs: 1.25, the universal price of garlic

Debug effectively with JSON.parse

Pro debugging tip: Display the type and value of the soon-to-be parse victim when a JSON error occurs. They're the usual suspects.

try { JSON.parse(products); // If 'products' is not a string, it's a banana peel! } catch (e) { console.error("Type:", typeof products); console.error("Value:", products); // These debug logs help you see through the Matrix throw e; }