うさぎ好きエンジニアの備忘録

うさぎたちに日々癒されているエンジニアが業務で直面したもの & 個人的な学習メモを残していきます。

jsonlintでJSONの構文チェックをしてみる。

タイトルの通り。

JSONの構文チェックをしたくなったので備忘録を残しておきます。

jsonlintのインストール

(npmが使える環境でお願いします。)

$ npm install jsonlint -g

インストールが終わったら試しにヘルプとか表示して、正常にインストールされているか確認。

$ jsonlint --help

Usage: jsonlint [file] [options]

file     file to parse; otherwise uses stdin

Options:
   -v, --version            print version and exit
   -s, --sort-keys          sort object keys
   -i, --in-place           overwrite the file
   -t CHAR, --indent CHAR   character(s) to use for indentation  [  ]
   -c, --compact            compact error display
   -V, --validate           a JSON schema to use for validation
   -e, --environment        which specification of JSON Schema the validation file uses  [json-schema-draft-03]
   -q, --quiet              do not print the parsed json to STDOUT  [false]
   -p, --pretty-print       force pretty printing even if invalid

構文チェックしてみる。

適当なJSONを用意。

$ cat test.json
[
  {
    "hogehoge": 1,
    "fugafuga": true
  }
]

正常な場合はこんな感じの出力になります。(-qで余計な出力を消してます。)

$ jsonlint test.json -q

$ echo $?
0

だめな場合は怒ってくれました。

$ cat test.json
[
  {
    "hogehoge": 1,
    "fugafuga": true,
  }
]

$ jsonlint test.json -q
Error: Parse error on line 4:
..."fugafuga": true,  }]
----------------------^
Expecting 'STRING', got '}'
    at Object.parseError (/home/ponteru/.nodebrew/node/v12.13.0/lib/node_modules/jsonlint/lib/jsonlint.js:55:11)
    at Object.parse (/home/ponteru/.nodebrew/node/v12.13.0/lib/node_modules/jsonlint/lib/jsonlint.js:132:22)
    at parse (/home/ponteru/.nodebrew/node/v12.13.0/lib/node_modules/jsonlint/lib/cli.js:82:14)
    at main (/home/ponteru/.nodebrew/node/v12.13.0/lib/node_modules/jsonlint/lib/cli.js:135:14)
    at Object.<anonymous> (/home/ponteru/.nodebrew/node/v12.13.0/lib/node_modules/jsonlint/lib/cli.js:179:1)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)