sgarza62 sgarza62 - 3 months ago 7
Git Question

Emacs mode or validation tool to help detect errors in JSON files?

I want to ensure my JSON file is properly formatted before git pushing. I use emacs; is there a mode that helps detect syntax errors? Otherwise, is there some parser/validator that I can setup to run on changed

.json
files?

Example of syntax error: comma after the last value of an object.

Thanks!

EDIT: For security reasons, I won't copy-and-paste the JSON into third-party JSON validation websites.

Answer

This is the solution I ended up using.

Just paste the below code into your directory's .git/hooks/pre-commit file. Then, chmod +x the file.

#!/bin/sh

files=$(git diff --cached --name-only --diff-filter=ACM | grep ".json$")
if [ "$files" = "" ]; then
    exit 0
fi

pass=true

echo "\nValidating Modified JSON Files:\n"

for file in ${files}; do
    result=$(jslint ${file} | grep "${file} is OK")
    if [ "$result" != "" ]; then
        echo "\t\033[32mJSLint Passed: ${file}\033[0m"
    else
        echo "\t\033[31mJSLint Failed: ${file}\033[0m"
        pass=false
    fi
done

echo "\nJSON Validation Complete\n"

if ! $pass; then
    echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains JSON files do not pass . Please fix the JSLint errors and try again.\n"
    exit 1
else
    echo "\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi