The "Unexpected token" JSON error occurs when npm encounters an invalid character while parsing package.json. This typically indicates a syntax error at the reported position.
This error provides specific information about where JSON parsing failed. The "unexpected token" is the character that the parser didn't expect at that position. Common unexpected tokens include: } (extra closing brace), , (trailing comma), ' (single quote), or even invisible characters. The position number tells you exactly where in the file the error occurred, though it counts from the start of the file including whitespace.
Use the position to locate the error:
# Count to position in file
head -c 234 package.json | tail -c 20
# Or use Node
node -e "const fs=require('fs'); const c=fs.readFileSync('package.json','utf8'); console.log(c.substring(230,240))"Reveal invisible characters:
# Show all characters including hidden
cat -A package.json
# Or use hexdump
hexdump -C package.json | headLook for unexpected byte sequences.
Check and remove BOM:
# Check for BOM (EF BB BF)
file package.json
head -c 3 package.json | xxd
# Remove BOM
sed -i '1s/^\xEF\xBB\xBF//' package.jsonCreate a clean version:
# Parse and rewrite
node -e "const p=require('./package.json'); console.log(JSON.stringify(p,null,2))" > package.json.new
mv package.json.new package.jsonOr manually copy content to new file.
Replace smart quotes with regular:
# Using sed
sed -i "s/[\u201c\u201d]/\"/g" package.json
sed -i "s/[\u2018\u2019]/'/g" package.jsonOpen in VS Code:
1. File shows syntax errors with red underlines
2. Check "Select Encoding" in status bar
3. Choose "UTF-8" without BOM
4. Save file
When receiving package.json from others, always validate before use. CI/CD should validate JSON files as part of linting. Configure your editor to show invisible characters and use UTF-8 without BOM. Windows Notepad used to add BOM - modern versions fixed this. Git can help detect encoding issues with .gitattributes.
npm notice access token expired or revoked. Please try logging in again.
Token has expired - npm authentication failure
npm ERR! code EAI_AGAIN
How to fix "EAI_AGAIN" in npm
npm error code E403 npm error 403 Forbidden - PUT https://registry.npmjs.org/<package>
How to fix 'E403 Forbidden' error in npm
npm ERR! code EUSAGE npm ERR! Usage error
How to fix "npm ERR! code EUSAGE" in Node.js projects
npm ERR! code E401 npm ERR! 401 Unauthorized
How to fix "E401 Unauthorized" in npm