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.
Fixes npm ERR! Unexpected token in JSON at position
# 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))"# Count to position in filehead -c 234 package.json | tail -c 20# Or use Nodenode -e "const fs=require('fs'); const c=fs.readFileSync('package.json','utf8'); console.log(c.substring(230,240))"npm ERR! Unexpected token in JSON at 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.