Thursday, June 5, 2014

JSON file validator locally

JSON files are great for many things, but they can also be the root of very strange issues. Hence, you should always validate your JSON files whenever you update them to ensure you don't spend hours debugging issues that a really caused by a simple error in a JSON file (yes, I talk from experience).

Validating a JSON file is easy. There are many good online ones, like http://jsonlint.com/. However, if you want to validate many files, it is cumbersome, or if you have sensitive data in your JSON file, you may not want to copy/paste that to a public site.

The solution is simple. Simply install a JSON validator / checker locally. And they also allow for “pretty printing” of your JSON too.  There are a few ways to skin this cat.

Steps (jsonlint):
  1. Install NPM. Part of nodejs. Get it from http://nodejs.org/download/
  2. Get jsonlint from https://www.npmjs.org/package/jsonlint
  3. Reboot (if on Windows)
To run simply open a prompt and type “jsonlint FILE” or "jsonlint -h" to see options.
For multiple files, script it. E.g. on Windows use “for %i in (content\*.json) do jsonlint -q %i

Steps (Cygwin):
  1. Make sure that Python is installed.
To run simply open a Cygwin prompt and type “cat FILE | python -mjson.tool”.
For multiple files, script it. E.g. in BASH “for FILE in content/*.json \n do \n cat $FILE | python -mjson.tool \n done

Nifty,
Thomas