DEV Community

Bobo
Bobo

Posted on

Validate JSON Like a Pro: Catch Syntax Errors Before They Break Your App

Validate JSON Like a Pro: Catch Syntax Errors Before They Break Your App

A single missing comma in a JSON config file can take down your entire application. Here's how to validate JSON files before they cause damage.

Install json-tidy

npm install -g json-tidy-pro
Enter fullscreen mode Exit fullscreen mode

Validate Single File

json-tidy validate config.json
# ✅ Valid JSON!
Enter fullscreen mode Exit fullscreen mode

Validate Multiple Files

json-tidy validate config/*.json
# ✅ config.json: Valid
# ❌ database.json: Invalid - missing comma at line 42
# ✅ routes.json: Valid
Enter fullscreen mode Exit fullscreen mode

Integrate into Git Hooks

# .git/hooks/pre-commit
#!/bin/bash
npx json-tidy validate config/*.json
if [ $? -ne 0 ]; then
    echo "❌ Invalid JSON detected. Fix before committing."
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode

Integrate into CI/CD

# .github/workflows/validate.yml
name: Validate JSON
on: [push]
jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: npx json-tidy validate ./config/**/*.json
Enter fullscreen mode Exit fullscreen mode

Common JSON Errors json-tidy Catches

  • Missing commas in objects and arrays
  • Trailing commas (not allowed in strict JSON)
  • Unquoted property names
  • Single quotes instead of double quotes
  • Comments (not valid in JSON)
  • Extra trailing content

Install

npm install -g json-tidy-pro
Enter fullscreen mode Exit fullscreen mode

🌐 Visit us: https://www.tucaowall.vip/
☁️ Get free DigitalOcean credit: https://m.do.co/c/fc5cb7b29a0d

Have a JSON horror story? Share it in the comments!

Top comments (0)