Quick JSON validation with Python

A while ago I was spending a bunch of time with PowerShell, but these days Python is more commonly my scripting language (or bash or zsh, if I can get away with it).

There was a post on Quick JSON Validation that I thought was worth revamping.

The json library includes methods for parsing and formatting objects, and includes a command-line interface, so if you simply want to check whether a file has valid JSON, you can run the following:

python -mjson.tool somefile

This will print out the contents. If you are scripting this, you can redirect to /dev/null and just check the exit code.

If you're looking for the Python code to actually do this the way I did it in PowerShell, that's pretty straightforward too.

import json
with open("myfile.json") as file:
  s = file.read()
print(json.loads(s))

Happy validation!

Tags:  python

Home