{}JSON FYI

How to validate JSON in JavaScript, Python, and Bash

Idiomatic snippets for the three languages you reach for most when wrangling JSON.

·7 min read

JavaScript / TypeScript

function isValidJson(s) {
  try { JSON.parse(s); return true; }
  catch { return false; }
}

For schema validation, use Ajv: npm i ajv.

Python

import json
try:
    json.loads(s)
    print("ok")
except json.JSONDecodeError as e:
    print(f"bad json at line {e.lineno} col {e.colno}: {e.msg}")

Bash (with jq)

echo "$payload" | jq empty && echo ok || echo "invalid JSON"

In the browser, no library

The same JSON.parse trick works. JSON FYI goes further: a custom tokenizer that produces precise line/column errors and lint warnings on top of the spec.

Frequently asked questions

Why doesn't JSON.parse give me line numbers?+

The spec doesn't require them. V8 added some, but they're inconsistent across browsers. Custom parsers like JSON FYI's give you reliable positions.

Related tools & guides