Overview

It is easy to make mistakes in a JSON file by simply missing a comma or other punctuation mark. A simple command line tool to check the syntax will be helpful to make sure the syntax is correct before even starting to use the file.

The tool

This simple tool is written in ruby and uses the “json” rubygem. Any version should be fine. Make sure the gem is installed before attempting to use this tool.

1
gem install json

Once the gem is installed, place the contents of the following block into a file (example: /usr/local/bin/jsonlint). Once the file is saved, make the file executable.

1
chmod +x /usr/local/bin/jsonlint

Note: If you do not have permission to edit/modify files in this location, execute the commands using sudo.

If you prefer saving the file in a different location, make sure the file is in your PATH or add the location to the PATH.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env ruby

require "rubygems"
require "json"

if ARGV.size < 1
  puts "Please provide a JSON file"
  exit 1
end

file_name = ARGV.shift

begin
  JSON.load(File.read(file_name))
  puts "Syntax OK"
  exit 0
rescue JSON::ParserError
  puts "Syntax Error!"
  exit 1
end

Tool in action

Here is a simple valid JSON file:

1
2
3
4
5
{
    "example": {
        "title": "This is an example"
    }
}

Running the lint tool against this file gives:

1
2
Kannans-MacBook-Pro:~ kannanmanickam$ jsonlint test.json
Syntax OK

Here is a JSON file that misses a “}”

1
2
3
4
{
    "example": {
        "title": "This is an example"
}

Running the list tool against this file gives:

1
2
Kannans-MacBook-Pro:~ kannanmanickam$ jsonlint test.json
Syntax Error!

Comments